我有一个基于Windows,iOS和OSX构建的跨平台应用程序。
在我的Windows应用程序中,我创建了一个初始状态为unsignalled的Event对象。我有一个线程,等待通过调用WaitForSingleObject()来发出此事件的信号。 WaitForSingleObject()阻塞线程的处理,直到另一个线程调用SetEvent()为止。
如何使用GCD dispatch_semaphore_wait()和dispatch_semaphore_signal()实现相同的行为?
我尝试过以下方法:
子线程:
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 );
}
主线程:
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 );
答案 0 :(得分:2)
这基本上是正确的,尽管你通常会dispatch_semaphore_create(0)
(这意味着dispatch_semaphore_wait
会等到它收到dispatch_semaphore_signal
;即它是“一个初始状态为unsignalled的对象“)。如果您使用1
,则会立即满足对dispatch_semaphore_wait
的第一次调用,而不是实际等待任何信号(尽管在调用BigSoundBufferUpdate
一次后,for
的第二次迭代循环将等待信号)。