1: Global chứa main
(0...5).forEach { (value) in DispatchQueue.main.async { print(value) print("This is a \(value * 10)") DispatchQueue.global(qos: .background).async { print("Day la b \(value * 1000)") print("That is c \(value * 1000000)") } } }
Kết quả trả về như sau:
0This is a 01This is a 102This is a 203This is a 304This is a 405This is a 50Day la b 0Day la b 1000That is c 1000000Day la b 2000That is c 2000000That is c 0Day la b 3000That is c 3000000Day la b 4000That is c 4000000Day la b 5000That is c 5000000
những dòng đang ở main vẫn từ trên xuống, những dòng ở background sẽ bị chạy lộn xộn.
2. Main > Global > Main:
(0...5).forEach { (value) in DispatchQueue.main.async { print(value) print("This is A \(value * 10)") DispatchQueue.global(qos: .background).async { print("Day la B \(value * 1000)") print("That is C \(value * 100000)") DispatchQueue.main.async { print("These are D \(value * 100000000)") print("Those are E \(value * 10000000000000)") print("Shift is F \(value * 1000000000000000000)") } } } }
Kết quả là:
0This is A 01This is A 102This is A 203This is A 304This is A 405This is A 50Day la B 0That is C 0Day la B 1000Day la B 2000These are D 0Those are E 0Shift is F 0That is C 200000Day la B 3000That is C 100000Day la B 4000That is C 300000Day la B 5000These are D 200000000Those are E 20000000000000Shift is F 2000000000000000000That is C 400000These are D 100000000Those are E 10000000000000That is C 500000Shift is F 1000000000000000000These are D 400000000Those are E 40000000000000Shift is F 4000000000000000000These are D 500000000Those are E 50000000000000Shift is F 5000000000000000000These are D 300000000Those are E 30000000000000Shift is F 3000000000000000000
Nó sẽ chạy như sau:
Cái phần thuộc về main vẫn thứ tự, đến khi nhảy đến đoạn code .background thì tất cả những đoạn code trong đó đều loạn xì ngầu NHƯNG những phần loạn sẽ là:
B,C và nhóm (D,E,F) và trong nhóm DEF mọi thứ vẫn theo thứ tự.