gpt4 book ai didi

c - Linux,C : how can I get return value from thread which greate than 4G in a 32bits OS?

转载 作者:行者123 更新时间:2023-11-30 18:29:22 25 4
gpt4 key购买 nike

我正在运行 32 位 操作系统。现在我创建的线程将返回一个int值,它可能大于4G​​。如何通过 pthread_join() 从我的 main() 函数接收此值?看起来在 32 位 系统中,(void *) 是 4 个字节。

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

void* thread_function(void)
{
uint64_t nbytes = 0;
//assign values to nbytes, it could be larger than 4G.
return (void *)nbytes;
}

int main()
{
pthread_t thread_id;
uint64_t nbytes;

pthread_create (&thread_id, NULL, &thread_function, NULL);
pthread_join(thread_id,(void**)&nbytes);
}

最佳答案

像这样:

void* thread_function(void *)
{
uint64_t nbytes = 0;
//assign values to nbytes, it could be larger than 4G.

void *retval = malloc (sizeof (nbytes));
memcpy (retval, &nbytes, sizeof (nbytes));
return retval;
}

int main()
{
pthread_t thread_id;
uint64_t nbytes;

pthread_create (&thread_id, NULL, &thread_function, NULL);

void *ret;
pthread_join(thread_id, &ret);
memcpy (nbytes, ret, sizeof (nbytes));
free (ret);
}

这是将值从一个线程传输到另一个线程的常见模式。发送线程分配内存、复制值并传递指针。接收线程获取指针,复制出值并释放指针。

关于c - Linux,C : how can I get return value from thread which greate than 4G in a 32bits OS?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38798083/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com