gpt4 book ai didi

c - pthread 中的意外输出

转载 作者:太空宇宙 更新时间:2023-11-04 07:33:37 25 4
gpt4 key购买 nike

您好,线程中的上述代码显示 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 的实际对象是 value,它是 main 函数的本地对象,因此在 main 之后访问已退出无效。

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

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

(我假设您在第二次调用 pthread_create 时打错了,并打算传递 thread2 而不是 thread1 .)

例如

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

关于c - pthread 中的意外输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10860436/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com