Câu hỏi phỏng vấn Swift
Câu hỏi

What is a Serial Queue?

Câu trả lời

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.

Key Characteristics of Serial Queues:

  1. Sequential Execution: Tasks are executed one after another. The next task in the queue will not start until the current task finishes.
  2. Thread Management: Although tasks are executed sequentially, they do not necessarily run on the same thread. The system manages the threads, and a serial queue can use different threads for different tasks over its lifetime, but never more than one thread at a time[3][5].
  3. Default Behavior: By default, a 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].

Example of Creating and Using a Serial Queue:

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")
}

Output:

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

junior

Gợi ý câu hỏi phỏng vấn

senior

What’s the difference between a static variable and a class variable?

junior

What is the difference between Upcast and Downcast in Swift?

senior

What’s the difference between Any and AnyObject ?

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào