我是C语言的新手,想尝试使用线程。我想使用 pthread_exit()
来从线程中返回某些值。
我的代码如下:
#include <pthread.h>
#include <stdio.h>
void *myThread()
{
int ret = 42;
pthread_exit(&ret);
}
int main()
{
pthread_t tid;
void *status;
pthread_create(&tid, NULL, myThread, NULL);
pthread_join(tid, &status);
printf("%d\n",*(int*)status);
return 0;
}
我希望程序输出"42\n"
,但它输出了一个随机数。如何打印返回的值?
看起来问题出在我返回了一个局部变量的指针。在多线程中返回/存储变量的最佳实践是什么?使用全局哈希表吗?