Unexpected output in pthread

怎甘沉沦 提交于 2020-01-03 05:13:51

问题


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);
}

回答1:


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);


来源:https://stackoverflow.com/questions/10860436/unexpected-output-in-pthread

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!