Reputation: 1686
I wrote a code to do some multithreading in order to benchmark my dd's writing/reading speed.
Everything is compiling and running fine, but I noticed that thread ID's were the same.
So I created a condition (see code comments), which surprisingly showed that every single thread I create has the same ID.
int main(int argc, char *argv[]) {
//long filesize = 10000000;
int nb_threads = atoi(argv[2]);
pthread_t tid[4];
int ok;
double latency;
double bandwith;
int err;
int i = 0;
srand(time(NULL));
while(i < nb_threads){
pthread_create(&(tid[i]),NULL,launch_dd_bm,(void *) argv);
pthread_join(tid[i], NULL);
/* if(!pthread_equal(tid[i],tid[i-1])){
printf("Thread ID: %u",tid[i]);
i++;
}
*/
i++;
}
return EXIT_SUCCESS;
}
void *launch_dd_bm(void *arg);
I know I am not testing if threads were successfully created, but they are. I just removed the conditions in the above code so you can really see what is going on.
Upvotes: 0
Views: 2423
Reputation: 883
You are calling pthread_join() immediately after creating the thread, so what happens is
the execution of the main thread halts and waits for the created thread to finish its
execution. When the first thread finishes, its Id is no longer in use and thus the same Id
"can be acquired" by a thread which is created afterwards. Thats the reason why all of
your threads have same Id.
To avoid this problem you should call pthread_join() outside the while loop.
Upvotes: 3
Reputation: 155465
pthread_create
stores the "id of the created thread". Thus thread IDs are only guaranteed to be unique among currently running threads, not among all the threads ever created in a process. Once a thread exits, its ID can be safely reused. This is analogous to how malloc
returns new pointers as long as you don't free them, at which point the ones you free may be reused.
If you need a really permanent ID, it is easy to implement a shared counter, e.g. by incrementing a global variable from launch_dd_bm
(and remembering to protect it with a mutex).
Upvotes: 2