如何从线程用C返回值 [英] How to return a value from thread in C

查看:128
本文介绍了如何从线程用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()

我的code是如下:

#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动态分配它(),并返回一个指针。当然,发起线程code届时将负责释放内存。

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返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆