C/线程,返回值

标签 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[])
{
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/

相关文章:

c - 如何扫描从另一个 C 程序运行的输出字符串值?

在两个指针的地址相同的情况下更改指针之一的值

c - C 中带有 pthreads 的两个矩阵的乘积

c++ - 编译时 -pthread 标志的意义

c++ - c++ : fread() 中奇怪的文件读取问题

java - 套接字通信中客户端接收到错误数据

c# - Windows Phone 8.1 中的后台线程

java - 如果我的值存储在线程安全映射中,该值是否需要是 ThreadLocal?

java - 如何保持 executorService 运行?

c++ - 跨线程发送 glib 信号