在pthread的意外输出 [英] Unexpected output in pthread

查看:124
本文介绍了在pthread的意外输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好用于线程以上code则显示为0(TID = 0),而不是8 ...可能是什么原因?在PrintHello功能我打印主题ID但我将值8,但它是印刷0作为输出

 的#include< pthreads.h中>
#包括LT&;&stdio.h中GT;
#包括LT&;&stdlib.h中GT;
无效* PrintHello(void *的主题ID)
{
   INT * TID;
   TID =主题ID;
   的printf(你好!世界是我,线#%d个\\ N!,* TID);
   了pthread_exit(NULL);
}INT主(INT ARGC,CHAR *的argv [])
{
   的pthread_t线程1,线程;
   INT RC;
   int值= 8;
   INT * T;
   T =&安培;价值;   的printf(在主:创建线程1);
    RC =在pthread_create(安培;线程1,NULL,PrintHello,(无效*)T);
     如果(RC)
    {
        的printf(ERROR;从pthread_create的收益code()为%d \\ n,RC);
        出口(-1);
        }
   的printf(在主:创建线程2 \\ n);
    RC =在pthread_create(安培;线程1,NULL,PrintHello,(无效*)T);
     如果(RC)
    {
        的printf(ERROR;从pthread_create的收益code()为%d \\ n,RC);
        出口(-1);
        }
   / *最后一件事是主要的()应该做的* /
   了pthread_exit(NULL);
}


解决方案

这包含实际的对象 8 这是您的本地功能后,使访问已退出是无效的。

您不要等到你的孩子线程完成他们试图这样的行为是未定义访问此局部变量之前。

一个解决将是让你的等待它使用退出前的子线程在pthread_join

(我假设你已经取得了你的第二个电话一个错字,以在pthread_create 键,旨在通过线程2 ,而不是线程1

例如

  / *主,在退出之前* /
在pthread_join(线程1,NULL);
在pthread_join(线程2,NULL);

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

解决方案

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

这篇关于在pthread的意外输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆