2012-12-20 23 views
0

線程我想解釋一下我想做的事通過使用並行線程取消在Objective-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; 
} 

所以上面的C語言是什麼,我想在Objective-C的事情。這是我在Objective-C使用它來創建線程:

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

由於我不聲明並初始化像線程id什麼,我不知道如何從另一個線程取消一個線程。有人可以將我的C代碼轉換爲Objective-C或向我推薦其他東西嗎?

回答

0

試試這個。

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

我爲什麼要取消當前線程?如果你看看我提供的代碼片段,我從threadTwo中取消了threadOne ...這絕對是一個錯誤的答案! –

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

請注意,像pthreads,NSThread取消是諮詢;這取決於您的代碼在該線程中運行以檢查線程的isCancelled狀態並進行相應的響應。 (你可以用類方法currentThread參考當前正在運行的NSThread。)