✍️ 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()
    }
}

Leave a comment

Quote of the week

"People ask me what I do in the winter when there's no baseball. I'll tell you what I do. I stare out the window and wait for spring."

~ Rogers Hornsby