Search code examples
objective-ccocoagrand-central-dispatchobjective-c-blocks

Is it good practice to send a delayed semaphore_signal to a semaphore in a macOS Grand Central Dispatch App?


I am using semaphores and GCD in a macOS Objective-C Application. I have this common scenario :

dispatch_semaphore_t fd_sema = dispatch_semaphore_create(0);

dispatch_async(dispatch_get_main_queue(), ^{

        // Perform some activity
        // But can potentially never complete

        dispatch_semaphore_signal(fd_sema);
});

dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(10 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        dispatch_semaphore_signal(fd_sema);
});

dispatch_semaphore_wait(fd_sema, DISPATCH_TIME_FOREVER);

Basically, here I am trying to obtain a timeout on a operation. Given that the argument of dispatch_semaphore_wait can only be now or forever, I am using the dispatch_after block to implement a timeout. Do you think this is good practice or it can lead to problems and crashes ? Thanks for any help.


Solution

  • Where'd you get the idea that the timeout on dispatch_semaphore_wait() can only be now or forever? That's not correct. You can pass the result from dispatch_time() just like you're using with dispatch_after(). Therefore, there's no need to implement a timeout yourself.