我正在寻找iOS中多线程的等效模式,因为.NET中有用于脉冲和等待的模式。本质上,我希望后台线程在设置标志之前一直处于休眠状态,这实际上是将线程“踢”入操作。

它是loop + thread.sleep()的替代方法。可以在与执行处理的实际后台线程不同的线程上设置该标志。谢谢!

最佳答案

iOS和OS X上提供了各种不同的混合匹配线程API。您正在使用什么来创建线程?

最简单的建议是使用Grand Central Dispatch (GCD) semaphore

设置代码:

dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
// Then make sure your thread has access to this semaphore


线程代码:

dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
// Will block forever until the semaphore is triggered


触发码:

dispatch_semaphore_signal(semaphore);


更好的建议是:GCD已经管理了自己的线程池,因此请充分利用它,而不是增加自己的线程。使用dispatch_async在后台线程中运行一些代码非常容易。

07-27 19:09