Home > OS >  Deadlock in main thread when use semaphore ObjC
Deadlock in main thread when use semaphore ObjC

Time:11-29

I am new to Xcode and ObjectiveC and I am building a non-UI tool. I found my main thread will get hang forever and never wakeup when I am using semaphore in main thread

      dispatch_semaphore_t waitSem = dispatch_semaphore_create(0);

      dispatch_async(dispatch_get_main_queue(), ^{

        // do something else
        dispatch_semaphore_signal(waitSem);

      });

      dispatch_wait(waitSem, DISPATCH_TIME_FOREVER);

CodePudding user response:

No async tasks will be processed on the main queue while it is blocking inside dispatch_wait(). This includes the task that you queued.

dispatch_wait() from the main queue only makes sense if the semaphore condition will be met without the main queue running any code.

  • Related