0

POSスレッドで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 に答える