c/c++语言开发共享pthread中的意外输出

你好上面的代码在线程中显示0(tid = 0)而不是8 …可能是什么原因? 在PrintHello函数中,我正在打印threadid,但是我发送值为8,但是输出为0

#include  #include  #include  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 %dn", rc); exit(-1); } printf("In main: creating thread 2n"); rc = pthread_create(&thread1, NULL, PrintHello, (void *)t); if (rc) { printf("ERROR; return code from pthread_create() is %dn", rc); exit(-1); } /* Last thing that main() should do */ pthread_exit(NULL); } 

    保存8的实际对象是main函数本地的value ,因此在main退出后访问无效。

    在尝试访问此局部变量之前,不要等待子线程完成,因此行为未定义。

    一个解决方法是在使用pthread_join退出之前让main等待它的子线程。

    (我假设你在第二次调用pthread_create了一个拼写错误,并且意味着传递thread2而不是thread1 。)

    例如

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

      以上就是c/c++开发分享pthread中的意外输出相关内容,想了解更多C/C++开发(异常处理)及C/C++游戏开发关注计算机技术网(www.ctvol.com)!)。

      本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

      ctvol管理联系方式QQ:251552304

      本文章地址:https://www.ctvol.com/c-cdevelopment/549372.html

      (0)
      上一篇 2021年1月14日
      下一篇 2021年1月14日

      精彩推荐