Async不会阻塞当前的执行线程,反之Sync会阻塞。
Barrier需要等待上一个任务执行完成。
队列的执行效率比UnfairLock要慢,当使用相对安全与容易。
// Sync / Async / Barrier /
let dispatchQueueA = DispatchQueue(label: "A", attributes: .concurrent)
print("Task 1 begin")
dispatchQueueA.async { // Task1
for index in 0 ..< 5 {
sleep(2)
print("Task 1 - async \(index)")
}
}
print("Task 2 begin")
dispatchQueueA.sync { // Task2
for index in 0 ..< 5 {
sleep(1)
print("Task 2 - sync without barrier \(index)")
}
}
print("Task 3.1 begin")
dispatchQueueA.async(flags: .barrier) {
for index in 0 ..< 5 {
sleep(1)
print("Task 3.1 - async with barrier \(index)")
}
}
print("Task 3.2 begin")
dispatchQueueA.async(flags: .barrier) {
for index in 0 ..< 5 {
sleep(1)
print("Task 3.2 - async with barrier \(index)")
}
}
print("Task 4 begin")
dispatchQueueA.sync(flags: .barrier) { // Task3
// the tasks(sync, async) assigned before this block will be completed first
// then this task will execute and as it is sync task no other task will start until it finishes
for index in 0 ..< 5 {
sleep(1)
print("Task 4 - sync with barrier \(index)")
}
}
print("Task 5 begin")
dispatchQueueA.async { // Task4
for index in 5 ..< 10 {
sleep(1)
print("Task 5 - async \(index)")
}
}
print("Task 6 begin")
dispatchQueueA.sync { // Task5
for index in 5 ..< 10 {
sleep(1)
print("Task 6 - sync without barrier \(index)")
}
}
执行结果
Task 1 begin
Task 2 begin
Task 2 - sync without barrier 0
Task 2 - sync without barrier 1
Task 1 - async 0
Task 2 - sync without barrier 2
Task 2 - sync without barrier 3
Task 1 - async 1
Task 2 - sync without barrier 4
Task 3.1 begin
Task 3.2 begin
Task 4 begin
Task 1 - async 2
Task 1 - async 3
Task 1 - async 4
Task 3.1 - async with barrier 0
Task 3.1 - async with barrier 1
Task 3.1 - async with barrier 2
Task 3.1 - async with barrier 3
Task 3.1 - async with barrier 4
Task 3.2 - async with barrier 0
Task 3.2 - async with barrier 1
Task 3.2 - async with barrier 2
Task 3.2 - async with barrier 3
Task 3.2 - async with barrier 4
Task 4 - sync with barrier 0
Task 4 - sync with barrier 1
Task 4 - sync with barrier 2
Task 4 - sync with barrier 3
Task 4 - sync with barrier 4
Task 5 begin
Task 6 begin
Task 6 - sync without barrier 5
Task 5 - async 5
Task 6 - sync without barrier 6
Task 5 - async 6
Task 6 - sync without barrier 7
Task 5 - async 7
Task 6 - sync without barrier 8
Task 5 - async 8
Task 6 - sync without barrier 9
Task 5 - async 9