pthread中的意外输出

时间:2012-06-02 06:49:57

标签: c posix

Hello对于线程中的上述代码显示0(tid = 0)而不是8 ...可能是什么原因?在PrintHello函数中,我正在打印threadid,但是我发送值为8,但是它打印0作为输出

#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 个答案:

答案 0 :(得分:3)

包含8的实际对象valuemain函数的本地对象,因此在main退出后进行访问无效。

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

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

(我假设您在第二次致电pthread_create时输了一个拼写错误,并打算通过thread2代替thread1。)

E.g。

/* in main, before exiting */
pthread_join(thread1, NULL);
pthread_join(thread2, NULL);
相关问题