Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to determine if a dispatch semaphore is being waited on?

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];
        });
    });
like image 529
Shizam Avatar asked Apr 03 '13 22:04

Shizam


People also ask

What is semaphore wait time?

The maximum timeout that may be specified is 281 272 976 710 655 (2 ** 48 -1) microseconds. Any value larger than this, other than 0xFFFFFFFF FFFFFFFF, will cause sem_wait_np() to wait for the maximum timeout (281 272 976 710 655 microseconds).

What is dispatch 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.

How does DispatchSemaphore work?

DispatchSemaphore allows only one thread to access shared resources at a time. And the order of uses of resources is (FIFO), who asks first get the resource first. Semaphores contain threads queues and a counter value integer type. Thread queue: it is used to keep track of waiting threads in the queue in FIFO order.


1 Answers

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 ?

like image 131
das Avatar answered Oct 04 '22 00:10

das