0
let semaphore = DispatchSemaphore(value: 1) 
DispatchQueue.global(qos: .background)

Does this mean if i use this semaphore to make a specific block of resource to be accessed by only one thread at a time, it will block the entire threads running in the background ( or ) only blocks the threads that demands the resources

Rob Napier
  • 286,113
  • 34
  • 456
  • 610

2 Answers2

2

It will block only the threads that demand already allocated resources. Whenever a thread calls,

@discardableResult func signal() -> Int 

semaphore count is incremented by 1 and that thread is given access to the critical section. If an upcoming thread calls the same method it will be blocked until the first thread calls

func wait()

method.

Shreeram Bhat
  • 2,849
  • 2
  • 11
  • 19
2

Semaphores are just managers that manage the execution of the threads that you ask them to. So, unless you call the semaphore on a particular thread, the thread has nothing to do with the semaphore. So you don't have to worry about the other threads getting blocked

If the semaphore is occupied, the next thread is set to wait() and is hence frozen till it gets the signal(). Hence, just don't mess with the main thread :-)

Lokesh SN
  • 1,583
  • 7
  • 23