问题描述
似乎这些是使NSThread休眠的唯一方法
Seems these are the only methods to put a NSThread to sleep
* sleepForTimeInterval:
* sleepUntilDate:
这是不好的做法我要求吗?
Would it be bad practice what I am asking?
推荐答案
你想让你的线程停止,直到某些其他线程告诉它再次启动?如果是这样,您可以使用NSConditionLock。 NSConditionLock类似于条件变量。它有几个基本方法,lockWhenCondition和unlockWithCondition,并锁定。一个典型的用法是让你的后台线程等待条件锁定lockWhenCondition:,并在你的前台线程设置条件,这导致后台线程被唤醒。条件是一个简单的整数,通常是枚举。
Do you want your thread to just stop until some other thread tells it to start up again? If so, you could use an NSConditionLock. An NSConditionLock is similar to a condition variable. It has a couple of basic methods, lockWhenCondition, and unlockWithCondition, and lock. A typical usage is to have your background thread waiting on the condition lock with "lockWhenCondition:", and the in you foreground thread to set the condition, which causes the background thread to wake up. The condition is a simple integer, usually an enumeration.
这里有一个例子:
enum {
kWorkTodo = 1,
kNoWorkTodo = 0
}
- (id)init {
if ((self = [super init])) {
theConditionLock = [[NSCoditionLock alloc] initWithCondition: kNoWorkTodo];
workItems = [[NSMutableArray alloc] init];
}
}
- (void)startDoingWork {
[NSThread detachNewThreadSelector:@selector(doBackgroundWork) toTarget:self withObject:nil];
}
- (void)doBackgroundWork:(id)arg {
while (YES) {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSArray *items = nil;
[theConditionLock lockWhenCondition:kWorkTodo]; // Wait until there is work to do
items = [NSArray arrayWithArray:workItems]
[workItems removeAllObjects];
[theConditionLock unlockWithCondition:kNoWorkTodo];
for(id item in items) {
// Do some work on item.
}
[pool drain];
}
}
- (void)notifyBackgroundThreadAboutNewWork {
[theConditionLock lock];
[workItems addObject:/* some unit of work */];
[theConditionLock unlockWithCondition:kWorkTodo];
}
在这个例子中,当startDoingWork被调用doBackgroundWork:将会在后台线程,但随后停止,因为没有任何工作要做。一旦notifyBackgroundThreadAboutNewWork被调用,然后doBackgroundWork:将启动并处理新的工作,然后回到睡眠等待新的工作可用,这将发生在下一次notifyBackgroundThreadAboutNewWork被调用。
In this example, when startDoingWork is called doBackgroundWork: will start on a background thread, but then stop because there isn't any work to do. Once notifyBackgroundThreadAboutNewWork is called, then doBackgroundWork: will fire up and process the new work, and then go back to sleep waiting for new work to be available, which will happen the next time notifyBackgroundThreadAboutNewWork is called.
这篇关于有没有办法暂停一个NSTHread无限期,并从另一个线程恢复?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!