[英]Unexpected output in pthread
您好上述线程中的代码显示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);
}
保留8
的实际对象是您的main
函数本地的value
,因此在main
退出后访问无效。
您不必等待子线程完成访问,然后再尝试访问此局部变量,因此行为未定义。
一种解决方法是让您的main
在使用pthread_join
退出之前先等待其子线程。
(我假设您在第二次调用pthread_create
打了错字,并打算传递thread2
而不是thread1
。)
例如
/* in main, before exiting */
pthread_join(thread1, NULL);
pthread_join(thread2, NULL);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.