我有一个跨平台的应用程序,建立在Windows,iOS和OSX上。iOS/OSX等价的SetEvent()和WaitForSingleObject()?
在我的Windows应用程序中,我创建了一个具有未标记初始状态的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);
与手头上的问题无关,但我假设您试图最大限度地提高跨代码库的跨平台兼容性,值得注意的是,如果您避免创建一般情况下编写iOS/MacOS上的多线程代码手动线程,而是更彻底地使用GCD。请参阅[从线程迁移](https://developer.apple.com/library/ios/documentation/General/Conceptual/ConcurrencyProgrammingGuide/ThreadMigration/ThreadMigration.html#//apple_ref/doc/uid/TP40008091-CH105-SW1)在_Concurrency编程指南._ – Rob