Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS/OSX Equivalent of SetEvent() and WaitForSingleObject()?

I have a cross-platform app that builds on Windows, iOS and OSX.

In my Windows app I create an Event object with an initial state of unsignalled. I have a thread which waits for this Event to be signalled by calling WaitForSingleObject(). WaitForSingleObject() blocks the processing of the thread until such time that another thread calls SetEvent().

How do I achieve the same behaviour with GCD dispatch_semaphore_wait() and dispatch_semaphore_signal() ?

I've tried the following:

Child thread:

void *UpdateThread( void *pParams )
{
  for( ;; )
  {
    // Decrease the semaphore count, similar to sem_wait()
    dispatch_semaphore_wait( g_hEvtNeedMore, DISPATCH_TIME_FOREVER );
    BigSoundBufferUpdate();
  }
}

// SetEvent() - Windows equivalent 
void SetEvent( dispatch_semaphore_t sem )
{
  // Increase semaphore count - similar to sem_post()
  dispatch_semaphore_signal( sem );
}

Main thread:

g_hEvtNeedMore = dispatch_semaphore_create( 1 ); // Not sure if initial value should be 0 or 1
pthread_create( &hUpdateThread, NULL, UpdateThread, NULL );
...


// Tell the child thread we want more data..
SetEvent( g_hEvtNeedMore );
like image 794
SparkyNZ Avatar asked Dec 16 '25 17:12

SparkyNZ


1 Answers

This is basically right, though you generally would dispatch_semaphore_create(0) (which means the dispatch_semaphore_wait will wait until it receives dispatch_semaphore_signal; i.e., it is "an object with an initial state of unsignalled"). If you use 1, the first call to dispatch_semaphore_wait will be satisfied immediately, not actually waiting for any signal (though after calling BigSoundBufferUpdate once, the second iteration of that for loop will wait for a signal).

like image 154
Rob Avatar answered Dec 19 '25 05:12

Rob



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!