如何从C中的pthread线程返回值? [英] How to return a value from pthread threads in C?
问题描述
我是C语言的新手,并且想玩一些线程.我想使用 pthread_exit()
I'am new to C and would like to play with threads a bit. I would like to return some value from a thread using 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",但它输出一个随机数.如何打印返回的值?
I would expect the program output "42\n" but it outputs a random number. How can I print the returned value?
根据第一个答案,问题是我正在返回指向局部变量的指针.返回/存储多个线程的变量的最佳实践是什么?全局哈希表?
According to first answers the problem is that I am returning pointer to local variable. What is the best practice of returning/storing variables of multiple threads? A global hash table?
预先感谢
推荐答案
您正在返回局部变量的地址,该局部变量的地址在线程函数退出时不再存在.无论如何,为什么要调用pthread_exit?为什么不简单地从线程函数返回值?
You are returning the address of a local variable, which no longer exists when the thread function exits. In any case, why call pthread_exit? why not simply return a value from the thread function?
void *myThread()
{
return (void *) 42;
}
然后在主目录中:
printf("%d\n",(int)status);
如果需要返回一个复杂的值(如结构),则最简单的方法是通过malloc()动态分配它并返回一个指针.当然,启动线程的代码将负责释放内存.
If you need to return a complicated value such a structure, it's probably easiest to allocate it dynamically via malloc() and return a pointer. Of course, the code that initiated the thread will then be responsible for freeing the memory.
这篇关于如何从C中的pthread线程返回值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!