0

我想通过使用带有 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 或向我推荐其他东西吗?

4

2 回答 2

0

尝试这个。

   -(void)threadOne
    {
        [[NSThread currentThread] cancel];
    }
于 2012-12-20T02:40:37.973 回答
0

类方法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.

请注意,与 pthread 一样,NSThread取消是建议性的;由您在该线程中运行的代码来检查线程的isCancelled状态并做出适当的响应。NSThread(您可以使用类方法获取对当前运行的引用currentThread。)

于 2012-12-20T02:41:35.490 回答