终止来自主线程(可可)的次线程, [英] terminating a secondary thread from the main thread (cocoa)
问题描述
我在可可框架的帮助下开发了一个用objective-c编写的小应用程序,我遇到了一个多线程问题。
如果有人可以帮助我如何从主线程终止辅助线程(工作线程),我真的很感激。
I'm working on a small app written in objective-c with the help of the cocoa framework and I am having a multithreading issue. I would really appreciate it if somebody could help me with some guidance on how terminate a secondary(worker) thread from the main thread?
- (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?
}
我在 apple's docs < a>但是此示例中缺少的是runloop输入源更改 exitNow 值的部分。
在我的应用程序中使用许多线程,所以我宁愿一个简单的解决方案(更少的开销),而不是一个更复杂的,能够轻松地管理多个线程,但更多的开销生成(例如,使用锁可能(?)而不是runloops)
Also, I won't be using many threads in my app so I would prefer a simple solution (with less overhead) rather than a more complex one that is able to manage many threads easily, but with more overhead generated (eg. using locks maybe(?) instead of runloops)
提前感谢
推荐答案
是使用NSThread的 - (void)cancel方法。你需要一个引用你创建的线程,以及。你的示例代码看起来像这样,如果你可以做一个循环的工作线程:
I think the easiest way is to use NSThread's -(void)cancel method. You'll need a reference to the thread you've created, as well. Your example code would look something like this, if you can do the worker thread as a loop:
- (IBAction)startWorking:(id)sender {
myThread = [[NSThread alloc] initWithTarget:self selector:@selector(threadMain:) object:nil];
[myThread start];
}
- (void)threadMain
{
while(1)
{
// do IO here
if([[NSThread currentThread] isCancelled])
break;
}
}
- (IBAction)stop:(id)sender {
[myThread cancel];
[myThread release];
myThread = nil;
}
当然,这只会取消循环迭代之间的线程。所以,如果你做一些长阻塞计算,你必须找到一种方法将它分解成块,所以你可以定期检查isCancelled。
Of course, this will only cancel the thread between loop iterations. So, if you're doing some long blocking computation, you'll have to find a way to break it up into pieces so you can check isCancelled periodically.
这篇关于终止来自主线程(可可)的次线程,的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!