-3

I have a simple program below where it prints the thread id of each thread created.

#include <stdio.h>
#include <pthread.h>
#define NUM_THREAD 5

void *runner(void *param);

int main()
{
     int i;
     pthread_t tid[NUM_THREAD];

     for(i = 0; i < NUM_THREAD; i++){
         pthread_create(&tid[i], NULL, runner, NULL);
         printf("%u\n", (unsigned int) pthread_self());
     }

//   for(i = 0; i < NUM_THREAD; i++)
//       pthread_join(tid[i], NULL);
}

void *runner(void *param)
{
    /* do some work */

    pthread_exit(0);
}

The code is running fine and giving me the right output.

1527895872
1527895872 
1527895872
1527895872
1527895872

My question is why are the thread ids the same?

1
  • Perhaps you meant to print tid[i] Jan 26, 2016 at 2:33

2 Answers 2

5

Because you are printing the thread id of main(), instead of the thread itself. You need to move the printf() to the code that runs as a thread i.e. runner().

#include <stdio.h>
#include <pthread.h>
#define NUM_THREAD 5

void *runner(void *param);

int main()
{
     int i;
     pthread_t tid[NUM_THREAD];

     for(i = 0; i < NUM_THREAD; i++){
         pthread_create(&tid[i], NULL, runner, NULL);
         // printf("%u\n", (unsigned int) pthread_self()); // <----- from here
     }

//   for(i = 0; i < NUM_THREAD; i++)
//       pthread_join(tid[i], NULL);
}

void *runner(void *param)
{
    printf("%u\n", (unsigned int) pthread_self()); // <-------- to here

    /* do some work */

    pthread_exit(0);
}
4

It is printing the id of the calling thread - http://man7.org/linux/man-pages/man3/pthread_self.3.html - this is the same thread each time in the loop;

Perhaps the printf should be moved to runner

1
  • 2
    Note that if you put the printf inside of runner the output thread ids won't necessarily be printed in the order that they were created. You would have to do extra work to synchronize the thread output.
    – bruceg
    Jan 26, 2016 at 2:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.