Why does pthread_self() return the same id multiple times?

linux, multithreading, posix, pthreads

Solution

Since only one of the created threads runs at a time, every new one gets the same ID as the one that finished before, i.e. the IDs are simply reused. Try creating threads in a loop and then joining them in a second loop.

However, you will then have to take care that each thread independently reads the content of `i`, which will give you different headaches. I'd pass the index as context argument, and then cast it to an int inside the thread function.

Problem

I am trying to create a number of threads (representing persons), in a for loop, and display the person id, which is passed as an argument, together with the thread id. The person id is displayed as exepected, but the thread id is always the same. ``` #include <stdio.h> #include <stdlib.h> #include <pthread.h> void* travelers(void* arg) { int* person_id = (int*) arg; printf("\nPerson %d was created, TID = %d", *person_id, pthread_self()); } int main(int argc, char** argv) { int i; pthread_t th[1000]; for (i=0; i < 10; i++) { if ((pthread_create(&th[i], NULL, travelers, &i)) != 0) { perror("Could not create threads"); exit(2); } else { // Join thread pthread_join(th[i], NULL); } } printf("\n"); return 0; } ``` The output I get is something like this: ``` Person 0 was created, TID = 881035008 Person 1 was created, TID = 881035008 Person 2 was created, TID = 881035008 Person 3 was created, TID = 881035008 Person 4 was created, TID = 881035008 Person 5 was created, TID = 881035008 Person 6 was created, TID = 881035008 Person 7 was created, TID = 881035008 Person 8 was created, TID = 881035008 Person 9 was created, TID = 881035008 ``` What am I doing wrong?

Original source