我正在使用Objective-C语言和Cocoa框架编写一个小型应用程序,遇到了多线程问题。我需要一些指导:如何从主线程中终止一个次要(工作)线程?
- (IBAction)startWorking:(id)sender {
[NSThread detachNewThreadSelector:@selector(threadMain:) toTarget:self withObject:nil];
}
- (void)threadMain
{
// do a lot of boring, time consuming I/O here..
}
- (IBAction)stop:(id)sender {
// what now?
}
我在苹果文档上找到了一些东西,但这个例子缺少了运行循环输入源改变exitNow值的部分。
此外,我的应用程序中不会使用太多线程,因此我更喜欢一个简单的解决方案(开销较小),而不是一个更复杂的解决方案,虽然能够轻松管理多个线程,但会产生更多的开销(例如,可能使用锁代替运行循环)。
提前感谢。