2016-04-22 53 views
3

我有一个跨平台的应用程序,建立在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); 
+1

与手头上的问题无关,但我假设您试图最大限度地提高跨代码库的跨平台兼容性,值得注意的是,如果您避免创建一般情况下编写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

回答

1

这基本上是正确的,但你通常会dispatch_semaphore_create(0)(这意味着dispatch_semaphore_wait将等待,直到它收到dispatch_semaphore_signal;即,它是“一个初始状态未标记的对象”)。如果您使用1,第一次调用dispatch_semaphore_wait将立即得到满足,而不是实际等待任何信号(尽管在调用BigSoundBufferUpdate一次后,该for循环的第二次迭代将等待信号)。

+0

感谢您的信任投票 - 我已经接受您的答案。 – SparkyNZ