duslabo
duslabo

Reputation: 1517

Unexpected output in pthread

Hello for above code in thread it is displaying 0 (tid = 0) instead of 8... what may be the reason ? In PrintHello function I am printing threadid but I am sending value 8 but it is printing 0 as output

#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>


void *PrintHello(void *threadid)
{
   int *tid;
   tid = threadid;
   printf("Hello World! It's me, thread #%d!\n", *tid);
   pthread_exit(NULL);
}

int main(int argc, char *argv[])
{
   pthread_t thread1,thread2;
   int rc;
   int value = 8;
   int *t;
   t = &value;

   printf("In main: creating thread 1");
    rc = pthread_create(&thread1, NULL, PrintHello, (void *)t);
     if (rc)
    {
        printf("ERROR; return code from pthread_create() is %d\n", rc);
        exit(-1);
        }


   printf("In main: creating thread 2\n");
    rc = pthread_create(&thread1, NULL, PrintHello, (void *)t);
     if (rc)
    {
        printf("ERROR; return code from pthread_create() is %d\n", rc);
        exit(-1);
        }


   /* Last thing that main() should do */
   pthread_exit(NULL);
}

Upvotes: 0

Views: 1062

Answers (1)

CB Bailey
CB Bailey

Reputation: 793269

The actual object that holds 8 is value which is local to your main function so accessing after main has exited is not valid.

You don't wait for your child threads to finish before they attempt to access this local variable so the behaviour is undefined.

One fix would be to make your main wait for it's child threads before exiting using pthread_join.

(I've assumed that you've made a typo in your second call to pthread_create and meant to pass thread2 instead of thread1.)

E.g.

/* in main, before exiting */
pthread_join(thread1, NULL);
pthread_join(thread2, NULL);

Upvotes: 3

Related Questions