相关疑难解决方法(0)

如何从C中的线程返回一个值

我是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",但它输出一个随机数.如何打印返回的值?

编辑: 根据第一个答案,问题是我返回指向局部变量的指针.返回/存储多个线程的变量的最佳做法是什么?全局哈希表?

提前致谢

c pthreads

48
推荐指数
4
解决办法
10万
查看次数

标签 统计

c ×1

pthreads ×1