I am having trouble with my threads. I am trying to create 10 threads and for each thread I want to print the thread ID. I am able to print the thread ID but the problem is that all threads prints out the same thread ID.
This is my code:
main:
int main(void)
{
int check_error;
pthread_t clientThread[10];
printf("creating a client thread..!n");
fflush(stdout);
for(int i=0; i<10;i++){
check_error=pthread_create(&clientThread[i], NULL, mqClient, NULL);
if(check_error!=0)
printf("Error when creating thread: %s", strerror(check_error));
else
pthread_join(clientThread[i], NULL);
}
return EXIT_SUCCESS;
}
mqClient:
void * mqClient(void * arg){
pthread_mutex_lock(&mutex);
mqd_t mq_on_server;
struct pt planet;
char thread_id[30];
sprintf(thread_id, "%d", pthread_self());
usleep(1000);
int response = MQconnect(&mq_on_server, "/servermq");
if(response==0){
printf("Something went wrong with MQconnectn");
}
else{
printf("nEnter planet name: ");
scanf("%s", planet.name);
printf("nEnter planet X-position: ");
scanf("%lf", &planet.sx);
printf("nEnter planet Y-position: ");
scanf("%lf", &planet.sy);
printf("nEnter planet X-velocity: ");
scanf("%lf", &planet.vx);
printf("nEnter planet Y-velocity: ");
scanf("%lf", &planet.vy);
printf("nEnter planet mass: ");
scanf("%lf", &planet.mass);
printf("nEnter planet life time: ");
scanf("%d", &planet.life);
strcpy(planet.pid, thread_id);
printf("id: %s", planet.pid);
printf("n---------------------------------------");
}
MQwrite (mq_on_server, &planet);
int c;
while ( (c = getchar()) != 'n' && c != EOF);
pthread_mutex_unlock(&mutex);
return NULL;
}
When testing two threads this is the output (observe the same thread ID):
Planet name: dsadas
Planet X-position: 321.000000
Planet Y-position: 321.000000
Planet X-velocity: 321.000000
Planet Y-velocity: 312.000000
Planet mass: 321.000000
Planet life time: 321
Planet thread ID: 1058301696
---------------------------------------
Planet name: ytyr
Planet X-position: 3123.000000
Planet Y-position: 54.000000
Planet X-velocity: 56.000000
Planet Y-velocity: 231.000000
Planet mass: 546.000000
Planet life time: 231
Planet thread ID: 1058301696
The thread ID should be unique for each thread, so any idea why I am getting this kind of output?
Advertisement
Answer
In your loop in main
you are creating 10 threads, but you don’t create them in parallel. You are creating one thread at a time, waiting for it to end, and only then proceeding with the loop. So you only create 0-1 threads at a time, but not 0-10 threads.
In general: two threads that exist at the same time have different IDs, but two threads that exist at different points in time can have the same ID.