开发者

Pthread return results

开发者 https://www.devze.com 2023-04-05 03:53 出处:网络
I have a question about returning results from a pthread executed function. Related code: void* thread_func(void* args)

I have a question about returning results from a pthread executed function.

Related code:

void* thread_func(void* args)
{
    float result = 0;
    // ...do something
    return (void*)&result;
}

// ... using code
float answer;
pthread_join(pthread_handle, &answer);

To me, this kind of solution doesn't seem like it should work safely because result would reside on the stack of thread_func and cease to exist after thread_func returns. However, in all the tests I've done it seems to 开发者_运维知识库work flawlessly. Is there something I'm misunderstanding about why this is safe? If not and my tests just happened to work due to some fluke, how do I safely get the return value back from thread_func safely?


This isn't safe. You simply got lucky (or rather unlucky). After the function ends all automatic variables are lost (thus pointers to them are useless).

  • Use malloc and return that memory
  • Use a static object (a global variable for instance)
  • Use memory passed by the function that will join

In conclusion use some memory that will survive after the function ends.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号