Junior — Middle
Can you explain the mechanism of synchronous operations in a sequential queue?
sobes.tech AI
Answer from AI
In iOS, a serial queue executes tasks strictly one at a time, in the order they are added. A synchronous operation (sync) on such a queue blocks the current thread until the task completes.
Working mechanism:
- When
queue.sync { ... }is called, the current thread passes the task to the queue and waits for it to finish. - In a serial queue, tasks are executed sequentially, so if
syncis called from the same thread that services the queue, a deadlock may occur.
Example:
let serialQueue = DispatchQueue(label: "com.example.serial")
serialQueue.sync {
print("Executing task 1")
}
print("Task 1 completed, continuing")
Here, the thread that called sync will be blocked until the task completes. This is useful when you need to perform work in the queue and wait for the result, but caution is required to avoid deadlocks within the queue itself.