gpt4 book ai didi

C/线程,返回值

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

我创建了一个线程,该线程应该返回发送给它的整数的 sqrt,它在返回 int 值时工作正常,但是当我想返回 double 或 float 值时,它返回一些疯狂的数字,如何更改?

这是运行良好的代码:

int* function(int* x) {

printf("My argument: %d \n", *x);
int *y = malloc(sizeof(int));
*y=sqrt(*x);
return y;
}

int main(int argc, char* argv[])
{
pthread_t thread;
int arg = 123;
int *retVal;


pthread_create(&thread, NULL, (void * ( * ) (void *))function, &arg);

pthread_join(thread, (void **) &retVal);
printf("Sqrt of our argument: %d\n", * retVal);
free(retVal);
return 0;

}

但是当我将其更改为:

double* function(int* x) {


double *y = malloc(sizeof(double));
*y=sqrt(*x);
printf("My argument: %d \n", *x);
return y;
}

int main(int argc, char* argv[])
{
pthread_t thread;
int arg = 123;
double *retVal;


pthread_create(&thread, NULL, (void * ( * ) (void *))function, &arg);

pthread_join(thread, (void **) &retVal);
printf("Sqrt of our argument: %d\n", * retVal);
free(retVal);
return 0;
}

它返回 1076244058

最佳答案

您的更改是错误的

printf("Sqrt of our argument: %d\n", * retVal);

必须是

printf("Sqrt of our argument: %f\n", * retVal);

我猜你的编译器会告诉你类似的事情

warning: format ‘%d’ expects argument of type ‘int’, but argument 2 has type ‘double *’ [-Wformat=]

顺便说一句,您的实现调用了未定义的行为转换函数:看看 this SO answer

正如已经建议的,您可以使用 arg 将值传递回 main,而不是从任务函数返回它。

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

void* function(void* x)
{
double *y = x;

*y = sqrt(*y);

return x;
}

int main(void)
{
pthread_t thread;
double arg = 123;
void *retVal = NULL;

pthread_create(&thread, NULL, function, &arg);

pthread_join(thread, &retVal);
printf("Sqrt of our argument using arg : %f\n", arg);

if (retVal != NULL)
{
printf("Sqrt of our argument using retVal: %f\n", *((double *)retVal));
}

return 0;
}

关于C/线程,返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43757090/

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