user3595632
user3595632

Reputation: 5730

What's the difference using only one pthread_t variables and multiple pthread_t variables?

I want to know differences of using different number of pthread_t variables.
Here is a simple code that I made :

#include <stdio.h>
#include <pthread.h>

void *thread(void *vargp);

int main(int argc, char **argv)
{
     pthread_t tid;

     for (int i = 0; i < 5; i++){
          int* a = malloc(sizeof(int));
          *a = i;
          pthread_create(&tid, NULL, thread, a);
     }

     if(pthread_join(tid, NULL) == -1){
          printf("error");
          exit(1);
     }
}

void *thread(void *vargp)
{
     int count = 1;
     for(int i = 0; i <3; i++){
          printf("count : %d, value : %d\n", count, (*(int *)vargp));
          count++;
     }
}

It works well as I mean to. However, what I thought strange is that it create 5 threads but using only one pthread_t variable !.. I saw some examples where using same number of pthread variables with number of thread it will create. For example, If I gonna create 5 threads like below, I have to create 5 length pthread_t array, like pthread_t tid[5] . Could you tell me what's differences? Thanks

Upvotes: 3

Views: 1979

Answers (2)

P.P
P.P

Reputation: 121397

pthread_t variable passed to pthread_create is a thread identifier and it can be reused as you please. So there's nothing wrong with the way you used the same idenitfier tid to create multiple threads. But you'll lose the identity of all other threads except the last one created using it as tid is continuously overwritten in the loop.

However, if you would like to receive an exit value from the thread (using pthread_join) or like to do some other operations such as detaching it (using pthread_detach -- you could create a thread in detached state or the thread itself can detach it), set/get scheduling parameters (using pthread_setschedparam, pthread_getschedparam) etc, from the main thread you can't do that since you don't have the thread's ID.

In short, the code is perfectly fine and you'll need to store the IDs (such as using an array tid[5] in your example) if you want to manipulate the threads from outside (as opposed to from within the thread -- a thread can get its ID using pthread_self()).

Upvotes: 4

David Barda
David Barda

Reputation: 1010

Lets assume you want to create 5 threads then execute some code at the main thread and then wait for all the other threads to end before returning from the main thread. In this case you will have to keep the pthread_t's for the future usage at pthread_join.

Upvotes: 2

Related Questions