The tasks(sync/async) assigned before a barrier sync task has been assigned, will be completed first. Then the barrier sync task will be executed exclusively and as it is a sync task no other task will start until it finishes.
Example of a sample concurrent queue with barrier/ non-barrier sync and async.
let dispatchQueueA = DispatchQueue(label: "A", attributes: .concurrent)
dispatchQueueA.async { // Task1
for index in 0 ..< 5 {
sleep(2)
print("Task 1 - async \(index)")
}
}
dispatchQueueA.sync { // Task2
for index in 0 ..< 5 {
sleep(1)
print("Task 2 - sync without barrier \(index)")
}
}
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 3 - sync with barrier \(index)")
}
}
dispatchQueueA.async { // Task4
for index in 5 ..< 10 {
sleep(1)
print("Task 4 - async \(index)")
}
}
dispatchQueueA.sync { // Task5
for index in 5 ..< 10 {
sleep(1)
print("Task 5 - sync without barrier \(index)")
}
}
Output of the above code - Task3(sync barrier) executed after Task1 and Task2 have been completed. After completing Task3(sync barrier), next assigned tasks(Task4,Task5) have been started.
Task 2 - sync without barrier 0
Task 1 - async 0
Task 2 - sync without barrier 1
Task 2 - sync without barrier 2
Task 2 - sync without barrier 3
Task 1 - async 1
Task 2 - sync without barrier 4
Task 1 - async 2
Task 1 - async 3
Task 1 - async 4
Task 3 - sync with barrier 0
Task 3 - sync with barrier 1
Task 3 - sync with barrier 2
Task 3 - sync with barrier 3
Task 3 - sync with barrier 4
Task 5 - sync without barrier 5
Task 4 - async 5
Task 5 - sync without barrier 6
Task 4 - async 6
Task 5 - sync without barrier 7
Task 4 - async 7
Task 5 - sync without barrier 8
Task 4 - async 8
Task 5 - sync without barrier 9
Task 4 - async 9