我刚刚开始阅读苹果的线程编程指南。
我正在启动一个线程并引用它
self.myThread = [[NSThread alloc] initWithTarget: self
selector: @selector(myThreadMain)
object: nil];
[self.myThread start];
并且 threadMain 看起来像文档中的示例代码。
我需要从主线程更改代码中的“exitNow”变量以终止该线程,但不知道如何。
myThreadMain 循环在不执行任何工作时需要休眠,但也不知道如何实现它。
文档说如果新线程不会立即死亡,我将需要至少一个输入源,但是新线程只需要接收“立即退出消息”和 performSelector:onThread: 调用。
我应该设置输入源吗?
- (void) myThreadMain
{
NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
BOOL exitNow = NO;
NSRunLoop* runLoop = [NSRunLoop currentRunLoop];
// Add the exitNow BOOL to the thread dictionary.
NSMutableDictionary* threadDict = [[NSThread currentThread] threadDictionary];
[threadDict setValue:[NSNumber numberWithBool:exitNow] forKey:@"ThreadShouldExitNow"];
// Install an input source.
// [self myInstallCustomInputSource];
while (!exitNow)
{
// Do one chunk of a larger body of work here.
// Run the run loop but timeout immediately if the input source isn't waiting to fire.
[runLoop runUntilDate:[NSDate date]];
// Check to see if an input source handler changed the exitNow value.
exitNow = [[threadDict valueForKey:@"ThreadShouldExitNow"] boolValue];
}
[pool release];
}
我将把一些工作交给这个线程
performSelector:onThread:withObject:
要执行的选择器需要定义如下,
但也不知道如何实现。
- (void) selectorToPerformInThread
{
for( int i = 0; i < 10; ++i )
{
do something;
**if(received a new "selectorToPerformInThread" call
when we are still in this loop)
break out and let the new "selectorToPerformInThread"
in order to run from the beginning of loop**
}
}
这是很多问题......
让我重申我的问题。
- 如何设置存储在 threadDict 中的“exitNow”变量。
- 如何设置线程以便在不需要工作时(当它不执行选择器时)休眠。
- 我应该设置一个输入源以使线程不会立即死亡吗?
- 如何设置运行循环,以便每次调用“performSelector”时,取消相同的选择器(如果它正在执行),并从头开始运行它?
提前致谢。