C/Threads,返回值

C/Threads,返回值,c,multithreading,pthreads,C,Multithreading,Pthreads,我创建了一个线程,它应该返回一个发送给它的整数的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[]) { pthr

我创建了一个线程,它应该返回一个发送给它的整数的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=]
顺便说一句,您的实现调用了未定义的行为转换函数:看看

如前所述,您可以使用
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;
}
#包括
#包括
#包括
void*函数(void*x)
{
双*y=x;
*y=sqrt(*y);
返回x;
}
内部主(空)
{
pthread\u t线程;
双精氨酸=123;
void*retVal=NULL;
pthread_create(&thread,NULL,function,&arg);
pthread_join(线程和返回);
printf(“使用arg的参数的Sqrt:%f\n”,arg);
如果(retVal!=NULL)
{
printf(“使用retVal的参数的Sqrt:%f\n”,*((double*)retVal));
}
返回0;
}

考虑
double*y=malloc(sizeof(*y))
双*返回…?哪里有不起作用的代码?如果看不到问题,我们无法告诉您问题出在哪里。将返回值设置为参数要容易得多,即使用线程参数(
arg
)保存参数,但让线程用结果覆盖它。强制转换函数是UB。不要那样做。使用包装函数。你的标题不会向任何人描述这个问题。请改进它。