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

Explain what is...

Câu trả lời

DispatchGroup is a feature of the Grand Central Dispatch (GCD) framework in Swift that allows developers to manage and synchronize multiple asynchronous tasks. It provides a mechanism to group tasks together and track their completion, enabling the execution of a block of code once all tasks in the group have finished. This is particularly useful when you need to perform several tasks concurrently and wait for all of them to complete before proceeding.

Key Methods of DispatchGroup

  1. enter(): This method is used to notify the DispatchGroup that a task has started. Each call to enter() must be balanced with a corresponding call to leave().

  2. leave(): This method signals that a task has completed. It decrements the internal counter of the DispatchGroup, which was incremented by enter().

  3. notify(queue:execute:): This method allows you to specify a closure that will be executed once all tasks in the group have completed. The closure is dispatched to the specified queue.

  4. wait(): This method blocks the current thread until all tasks in the group have completed. It can be useful in scenarios where you need to ensure that all tasks are finished before moving on, but it should be used cautiously to avoid blocking the main thread.

Example Usage

Here is a practical example of using DispatchGroup in Swift:

swift Copy
import Foundation

let dispatchGroup = DispatchGroup()

// Simulate an asynchronous task
func performTask(taskNumber: Int) {
    DispatchQueue.global().async {
        print("Task \(taskNumber) is starting")
        // Simulate some work
        sleep(UInt32(arc4random_uniform(4)))
        print("Task \(taskNumber) is completed")
        dispatchGroup.leave()
    }
}

// Start the tasks
dispatchGroup.enter()
performTask(taskNumber: 1)
dispatchGroup.enter()
performTask(taskNumber: 2)
dispatchGroup.enter()
performTask(taskNumber: 3)

// Notify when all tasks are completed
dispatchGroup.notify(queue: DispatchQueue.main) {
    print("All tasks are finished. Display the results here.")
}

// This will block the current thread until all tasks are completed
dispatchGroup.wait()

In this example, three tasks are started asynchronously. Each task calls dispatchGroup.enter() before starting and dispatchGroup.leave() upon completion. The dispatchGroup.notify(queue:) method is used to execute a closure on the main queue once all tasks have finished. The dispatchGroup.wait() method blocks the current thread until all tasks are done, ensuring that the subsequent code runs only after all tasks have completed.

Benefits of Using DispatchGroup

  • Synchronization: Ensures...
expert

expert

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

expert

What’s the difference between init?() and init() ?

senior

Can you rewrite this code using mutating function?

senior

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

Bình luận

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

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