问题描述
我有一个工作线程,我想做一点任务,然后暂停&等待来自另一个线程的ok,continue命令,然后暂停&等待等等。
I have a worker thread that I want to do one bit of its task, then pause & wait for the "ok, continue" command from another thread, then pause & wait, etc.
用例是:控制对象是一个视图,我想显示工作线程内部的信息,并允许我
The use case is: the controlling object is a view that I want to display information about what's going on inside the worker-thread, and allow me to "single-step" through the worker as it does it's thing.
在我的工人中,我所拥有的相当丑陋和沉重的东西是这样的:
The rather ugly and heavy-handed thing that I have in my worker is this:
NSLog(@"paused");
paused = YES;
while (paused)
{
[NSThread sleepForTimeInterval:0.25];
}
NSLog(@".. continuing");
...但我不禁想到必须有一个更好的方式,
...But I can't help but think that there must be a nicer way, perhaps involving NSLocks, or some such.
感谢!
b
推荐答案
查看和部分。代码将如下所示:
Look into NSCondition and the Conditions section in the Threading guide. The code will look something like:
NSCondition* condition; // initialize and release this is your app requires.
//Worker thread:
while([NSThread currentThread] isCancelled] == NO)
{
[condition lock];
while(partySuppliesAvailable == NO)
{
[condition wait];
}
// party!
partySuppliesAvailable = NO;
[condition unlock];
}
//Main thread:
[condition lock];
// Get party supplies
partySuppliesAvailable = YES;
[condition signal];
[condition unlock];
这篇关于如何暂停NSThread直到通知?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!