Swift, Dispatch Semaphore

Dispatch Semaphore for thread synchronization in Swift

✍️ Note

Some codes and contents are sourced from Apple’s official documentation. This post is for personal notes where I summarize the original contents to grasp the key concepts.

References

  • Apple official documents
  • Raywenderlich.com

An object that controls access to a resource across multiple execution contexts through use of a traditional counting semaphore.

A dispatch semaphore is an efficient implementation of a traditional counting semaphore. Dispatch semaphores call down to the kernel only when the calling thread needs to be blocked. If the calling semaphore does not need to block, no kernel call is made.

You increment a semaphore count by calling the signal() method, and decrement a semaphore count by calling wait() or one of its variants that specifies a timeout.

https://developer.apple.com/documentation/dispatch/dispatchsemaphore

It’s useful when you want to limit the number of task at a time.

Example. Set value 4

let semaphore = DispatchSemaphore(value: 4)

for i in 0...10 {
    DispatchQueue.global().async {
        semaphore.wait()
        print("✅ Start download: \(i)")
        URLSession.shared.downloadTask(with: URL(string: "https://picsum.photos/200")!) { location, resopnse, error in
            let tempFileLocation = location
            print("✅ download completed: \(i)")
            semaphore.signal()
        }.resume()
    }
}

Comments

Leave a Reply

Discover more from Shawn

Subscribe now to keep reading and get access to the full archive.

Continue reading