posix c 中的线程:通过传递线程从另一个线程终止 1 个线程

posix thread in c: terminating 1 thread from another using by passing threads

所以当我练习线程时,我意识到我们可以将值传递给线程。现在我想知道,我可以在创建时将线程传递给另一个线程吗?类似的东西;

int main(){
  pthread_t t1;
  pthread_t t2;

  pthread_create(&t1, NULL, counting, t2);
  pthread_create(&t2, NULL, waiting, &results);
//...
}

我的函数看起来像那样;

void* counting(void * arg) {
    pthread_t *t = arg;
    pthread_cancel(arg);
}

我这样做是因为 counting 线程完成后我想终止 waiting 线程。

您有两个问题:

1) t2 的值直到您第二次调用 pthread_create returns 才被设置。您需要更改两个 pthread_create 调用的顺序。

2) 由于线程需要一个void *,你需要传递一个void *。将 pthread_t 转换为 void * 是不安全的。一个常见的模式是 malloc 新结构,填充它,并将指向它的指针传递给新创建的线程。新创建的线程完成后可以free结构。 (您也可以将 &t2 转换为 void *,只要确保 t2 始终有效,否则取消引用您传递给新创建线程的指针是不安全的。 )

通过这两个更改,它应该可以工作。