我是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;
}
Run Code Online (Sandbox Code Playgroud)
我希望程序输出"42 \n",但它输出一个随机数.如何打印返回的值?
编辑: 根据第一个答案,问题是我返回指向局部变量的指针.返回/存储多个线程的变量的最佳做法是什么?全局哈希表?
提前致谢