2016-10-12 49 views
0

我运行一个函数doTask在另一个线程象下面这样:杀死另一个线程在我的情况

NSThread *otherThread = [[NSThread alloc] initWithTarget:self 
               selector:@selector(doTask) 
                object:nil]; 
[otherThread start]; 

... 
-(void)doTask{ 
    ... 
} 

什么是从当前线程杀otherThread的正确方法?

我知道[otherThread cancel]只是标志着otherThread应该被杀但不是真的杀死它。

+0

总是最好*要求*另一个线程终止,而不是*告诉*它。这样会更清洁。 – Droppy

+0

是的,我明白了,但在我的情况下,我可以让其他线程终止? –

+0

未知;这取决于类之间的关系。 – Droppy

回答

-1

在使计时器无效或停止线程当前正在运行的其他耗时操作之后,您可以调用[otherThread cancel]。如果你正确地清理并且调用取消它应该杀死线程。

+0

但是'exit'是一个类方法而不是NSThread中的一个实例方法。 –

+0

愚蠢的,我的错误。你在doTask里面运行什么样的任务? – Yord

0

doTask需要定期检查某个状态以查看是否需要尽早终止。一个简单的BOOL就够了。

@interface MyTask:NSObject 
@property(atomic) BOOL keepGoing; 
@end 

@implementation MyTask 
- (void) calculate 
{ 
    while(_keepGoing && _workQueueHasStuff) { 
     .... process some stuff .... 
    } 
    if (!_keepGoing) { 
     ... early termination ... 
    } else { 
     ... work queue depleted ... 
    } 
} 

或者,如S,S说,使用isCancelled/-cancel API如预期


不能从线程之外直接杀死一个线程。