What is a Serial Queue?
What is a Serial Queue?
A Serial Queue in Swift is a type of dispatch queue that ensures tasks are executed one at a time in the order they are added. This means that each task must complete before the next one begins, maintaining a strict sequence of execution. Serial queues are often used to synchronize access to shared resources or to ensure that tasks are performed in a specific order, preventing data races and ensuring thread safety.
DispatchQueue
in Swift is a serial queue unless specified otherwise. You can create a serial queue simply by initializing a DispatchQueue
without any attributes[4][6].let serialQueue = DispatchQueue(label: "com.example.serialQueue")
serialQueue.async {
print("Task 1 started")
// Simulate some work
Thread.sleep(forTimeInterval: 2)
print("Task 1 finished")
}
serialQueue.async {
print("Task 2 started")
// Simulate some work
Thread.sleep(forTimeInterval: 1)
print("Task 2 finished")
}
Task 1 started
Task 1 finished
Task 2 started
Task 2 finished
In this example, "Task 2" will only start after "Task 1" has finished, demonstrating the sequential execution of tasks in a serial queue[6][10].
junior
Gợi ý câu hỏi phỏng vấn
Chưa có bình luận nào