How to determine if a dispatch semaphore is being waited on?
grand-central-dispatch, ios, multithreading, objective-c, semaphore
Solution
`dispatch_semaphore_wait()` has only decremented the semaphore value if it returns 0.
If the timeout expired (i.e. it returns non-zero), the semaphore value has NOT been decremented.
Think of the decrement in the success case as taking ownership of one of the resources managed by the counting semaphore, if you signaled right after a successful wait, you would indicate that you have stopped using that resource right away, which is presumably not what you want.
What are you trying to do ?
Problem
How can you determine if a `dispatch_semaphore_t` is being waited on w/out causing a wait on it? I was initially thinking: ``` if ( dispatch_semaphore_wait(mySemaphore, DISPATCH_TIME_NOW) ) { NSLog(@"No more resources, wait"); } else { NSLog(@"Resources available, shouldn't wait"); } ``` But the act of doing `dispatch_semaphore_wait()` the semaphore is decremented so then I was thinking: ``` if ( dispatch_semaphore_wait(mySemaphore, DISPATCH_TIME_NOW) ) { NSLog(@"No more resources, wait"); } else { dispatch_semaphore_signal(mySemaphore); NSLog(@"Resources available, shouldn't wait"); } ``` Which has the end result of not decrementing the semaphore but seems like a hack, suggestions? EDIT As I was typing out what I'm doing and how I came to this conclusion I realized that I was indeed thinking about the solution the wrong way, I just wanted to know if I was waiting on a resource and be able to show a 'wait' dialog to the user. I think this is the correct way to do it: ``` [self showWait]; dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ dispatch_semaphore_wait(mySemaphore, DISPATCH_TIME_FOREVER); dispatch_async(dispatch_get_main_queue(), ^{ [self hideWait]; }); }); ```