✍️ 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
https://developer.apple.com/documentation/dispatch/dispatchsemaphoresignal()method, and decrement a semaphore count by callingwait()or one of its variants that specifies a timeout.

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