Junior — Middle
Have you ever worked with Dispatch Barrier mechanism for thread synchronization?
sobes.tech AI
Answer from AI
Yes, I have worked with Dispatch Barrier in GCD (Grand Central Dispatch) for thread synchronization in iOS.
Dispatch Barrier allows executing a block of code exclusively on a queue that supports barriers, usually on a concurrent queue. This means that all tasks submitted before the barrier complete, then the barrier block executes, and only after its completion do the remaining tasks continue.
Example of usage:
let queue = DispatchQueue(label: "com.example.concurrent", attributes: .concurrent)
queue.async {
print("Task 1")
}
queue.async {
print("Task 2")
}
queue.async(flags: .barrier) {
print("Barrier task — exclusive access")
}
queue.async {
print("Task 3")
}
This is useful when you need to ensure exclusive access to a shared resource for writing, while allowing parallel execution of read tasks.
Dispatch Barrier is a convenient way to synchronize without explicitly using locks.