取消Objective-C中的线程



我想解释我想通过pthreads

使用c语言做什么
pthread_t tid1, tid2;
void *threadOne() {
    //some stuff
}
void *threadTwo() {
    //some stuff
    pthread_cancel(tid1);
    //clean up          
}
void setThread() {
    pthread_attr_t attr;
    pthread_attr_init(&attr);
    pthread_create(&tid1,&attr,threadOne, NULL);
    pthread_create(&tid2,&attr,threadTwo, NULL);
    pthread_join(tid2, NULL);
    pthread_join(tid1, NULL);
}
int main() {
    setThread();
    return 0;
}

因此,以上是我在Objective-C中要做的。这是我在Objective-C中使用的内容来创建线程:

[NSThread detachNewThreadSelector:@selector(threadOne) toTarget:self withObject:nil];

由于我没有声明和初始化线程ID之类的内容,因此我不知道如何从另一个线程取消一个线程。有人可以将我的C代码转换为Objective-C还是向我推荐其他内容?

类方法detachNewThreadSelector:toTarget:withObject:不返回NSThread对象,但这只是一种便利方法。

[NSThread detachNewThreadSelector:@selector(threadOne) toTarget:self withObject:nil];

与:

几乎相同
NSThread *threadOne = [[NSThread alloc] initWithTarget:self selector:@selector(threadOne) object:nil];
[threadOne start];

除了后一种方法为您提供了指向创建的NSThread对象的指针,然后您可以在其上使用cancel

之类的方法。

请注意,像Pthreads一样,NSThread取消是建议;这取决于您在该线程中运行的代码,以检查线程的isCancelled状态并适当响应。(您可以使用类方法currentThread获得对当前运行的NSThread的引用。)

尝试这个。

   -(void)threadOne
    {
        [[NSThread currentThread] cancel];
    }

最新更新