c - 如何从 C 中的 pthread 线程返回一个值?

标签 c pthreads

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

我返回一个指向局部变量的指针似乎是个问题。返回/存储多线程变量的最佳实践是什么?全局哈希表?

最佳答案

这是一个正确的解决方案。在这种情况下,tdata 是在主线程中分配的,并且有空间供线程放置其结果。

#include <pthread.h>
#include <stdio.h>

typedef struct thread_data {
   int a;
   int b;
   int result;

} thread_data;

void *myThread(void *arg)
{
   thread_data *tdata=(thread_data *)arg;

   int a=tdata->a;
   int b=tdata->b;
   int result=a+b;

   tdata->result=result;
   pthread_exit(NULL);
}

int main()
{
   pthread_t tid;
   thread_data tdata;

   tdata.a=10;
   tdata.b=32;

   pthread_create(&tid, NULL, myThread, (void *)&tdata);
   pthread_join(tid, NULL);

   printf("%d + %d = %d\n", tdata.a, tdata.b, tdata.result);   

   return 0;
}

关于c - 如何从 C 中的 pthread 线程返回一个值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2251452/

相关文章:

杀死后C++线程还活着吗?

c - 堆损坏问题 - C

c++ - libgit2 - 两个文本 blob 的差异

c - 如何在一字节整数中存储2位、1位、1位和四位值

c - 删除链表中的第一个节点

c - 如何在客户端连接时将其两个两个连接

c++ - 引用类型的C++内存管理

c++ - 如何中断无限的 sigtimedwait?

c++ - 以安全的方式了解 pthread 线程是否处于事件状态

c - 测量 Mutex 和 Busy waiting 的效率