对于像这样的代码:
// Code in some object that will do work for an application:
- (BOOL)shouldBeRunning
{
[lockRunning lock];
BOOL shouldBeRunning= shouldRun;
[lockRunning unlock];
return shouldBeRunning;
}
- (void)stopRunning
{
[lockRunning lock];
shouldRun= FALSE;
[lockRunning unlock];
}
- (void)threadEntryPoint:(id)object
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSRunLoop *runLoop = [NSRunLoop currentRunLoop];
// From an example I saw awhile back:
// A runloop with no sources returns immediately from runMode:beforeDate:
// That will wake up the loop and chew CPU. Add a dummy source to prevent it.
NSMachPort *dummyPort = [[NSMachPort alloc] init];
[runLoop addPort:dummyPort forMode:NSDefaultRunLoopMode];
[dummyPort release];
[pool release];
while ([self shouldBeRunning])
{
NSAutoreleasePool *loopPool = [[NSAutoreleasePool alloc] init];
[runLoop runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];
[loopPool drain];
}
}
- (BOOL)startRunning:(NSError **)errorPtr
{
[self stopRunning]; // Stop if we are already running.
[runWorker release];
runWorker= [[NSThread alloc] initWithTarget:self selector:@selector(threadEntryPoint:) object:nil];
if(!runWorker)
return (FALSE);
// Start up the thread.
shouldRun= TRUE;
[runWorker start];
return TRUE;
}
- (void)doLotsOfStuff
{
// Some operation that is long and intensive
// that should be done in the background.
// This function will call the app delegate, which will display the
// results. It will also notify the app on completion.
}
- (void)doStuff
{
// Commented out for illustrative purposes.
//[self startRunning]; // Fire thread up.
[self performSelector:@selector(doLotsOfStuff) onThread:runWorker withObject:nil waitUntilDone:NO];
}
// Out in the delegate:
- (void)applicationDidFinishLaunching:(NSNotification*)aNotification
{
// Do setup....
[workObject startRunning]; // Start the worker thread in the worker object.
}
- (void)buttonHandler:(id)sender
{
[workObject doStuff];
}
因此,在应用程序中有一个按钮。用户按下它,任务将在工作线程上运行。该任务将向应用程序提供反馈。在这种情况下,该按钮将被禁用,直到任务完成。我只是不想显示所有这些代码。
使用编写的代码,如果我按下按钮一次,任务就会立即运行。通常,第二次按下按钮会产生相同的结果。然而,有时第二次按下,但几乎总是第三次或之后,会导致执行任务的显着延迟。我把debug语句放进去,可以观察到代码在线程上做了performSelector,然后有延迟,最后任务运行。
如果我取消注释 doStuff 中重新创建线程的行(使 applicationDidFinishLaunching 中的那行变得多余),那么它当然每次都能完美运行。
据我所知,线程正在进入无响应状态。
关于可能发生的事情有什么想法吗?设置和处理代码有什么明显错误吗?任何输入表示赞赏。