Search code examples
cmultithreadingposix

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


So as i am practicing threads, i realize that we can pass values to threads. Now i am wondering, Can i pass thread to another when creating. Something like that;

int main(){
  pthread_t t1;
  pthread_t t2;

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

and my function looks like that;

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

I am doing it because from the counting thread i want to terminate the waiting thread when it is done.


Solution

  • You have two issues:

    1) The value of t2 is not set until your second call to pthread_create returns. You need to change the order of the two pthread_create calls.

    2) Since the thread takes a void *, you need to pass it a void *. It's not safe to cast a pthread_t to a void *. A common pattern is to malloc new structure, fill it in, and pass a pointer to it to the newly-created thread. The newly-created thread can free the structure when it's done with it. (You could also cast &t2 to a void *, just be sure that t2 remains valid at all times because otherwise it's not safe to dereference the pointer you passed to the newly-created thread.)

    With those two changes, it should work.