How can multiple threads have the same thread ID?

Viewed 6276

I've got a question: can multiple threads have the same thread_id? (Of course not.) But my code is doing so. How is this possible?

#include<stdio.h>
#include<unistd.h>
#include<pthread.h>
#include<sys/types.h>

void* message(void* var){
    int t = (int)var;


    printf("\n%d- Hi I'm thread ID=%lu\n",t+1,(int unsigned long)pthread_self());
}

int main(void){
    pthread_t threads[10];
    int report[10];
    for(int i=0;i<10;i++){
        report[i] = pthread_create(&threads[i],NULL,message,(void*)i);
        pthread_join(threads[i],NULL);
    }
    return 0;
}

My code at (Ubuntu 17.04) showing this result

1- Hi I'm thread ID=3076250432

2- Hi I'm thread ID=3076250432

3- Hi I'm thread ID=3076250432

4- Hi I'm thread ID=3076250432

5- Hi I'm thread ID=3076250432

6- Hi I'm thread ID=3076250432

7- Hi I'm thread ID=3076250432

8- Hi I'm thread ID=3076250432

9- Hi I'm thread ID=3076250432

10- Hi I'm thread ID=3076250432
1 Answers
for(int i=0;i<10;i++){
    report[i] = pthread_create(&threads[i],NULL,message,(void*)i);
    pthread_join(threads[i],NULL);
}

You're creating a thread and then immediately joining it, waiting for it to finish. This causes the ten threads to be created sequentially rather than in parallel, allowing their IDs to be recycled.

If you create all ten threads before joining on them you'll see different IDs.

for(int i=0;i<10;i++){
    report[i] = pthread_create(&threads[i],NULL,message,(void*)i);
}

for(int i=0;i<10;i++){
    pthread_join(threads[i],NULL);
}
Related