在 C 中更改线程中的变量

标签 c multithreading variables pointers

我知道这是非常基础的,但我很难做到,而且英语不是我的母语,对于任何错别字,我深表歉意。

我的这个程序必须使用 2 个线程来计算前 999999 个数字的平方根之和。其中一个线程必须对这些对求和,另一个线程必须求和赔率。当更改线程中每个总和的变量时,我的问题就来了,我总是得到 2 个错误,甚至无法编译。我对指针很陌生,所以我猜问题就在那里。

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


void *calc_pairs(void *sum){

    int i;

    for(i=0;i<=999999;i=i+2){

            *sum += sqrt(i);
        }

    pthread_exit(NULL);

}

void *calc_odds(void *sum1){

    int a;

    for(a=1;a<999999;a=a+2){
                *sum1 += sqrt(a);
            }

    pthread_exit(NULL);

}


int main(int argc, char** argv) {

    pthread_t threads[2];

    double sum=0;
    double sum1=0;
    double sum_total;

    pthread_create(&threads[0],NULL, calc_pairs,(void *)&sum);
    pthread_create(&threads[1],NULL, calc_odds,(void *)&sum1);



    pthread_join(0);
    pthread_join(1);


    sum_total = sum1+sum;

    printf("The sum calculated on the threads is %f", sum_total);


    return (EXIT_SUCCESS);
}

我得到的错误是:

void 表达式的使用无效。警告:取消引用“void *”指针 [默认启用]

我计算平方的行中的两个错误。

最佳答案

首先,您没有将 void* 类型转换为 double*。第二个错误是将参数传递给 pthread_join 是错误的。这是您的工作代码。

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


void *calc_pairs(void *sum){

    int i;
    double *b;
    b=(double*)sum;
    for(i=0;i<=999999;i=i+2){

            *b += sqrt(i);
        }

       pthread_exit(NULL);

}

void *calc_odds(void *sum1){

    int a;
    double *b;
    b=(double*)sum1;
    for(a=1;a<999999;a=a+2){
                *b += sqrt(a);
            }

        pthread_exit(NULL);

    }


    int main(int argc, char** argv) {

    pthread_t threads[2];

    double sum=0;
    double sum1=0;
    double sum_total;

    pthread_create(&threads[0],NULL, calc_pairs,(void *)&sum);
    pthread_create(&threads[1],NULL, calc_odds,(void *)&sum1);



    pthread_join(threads[0],NULL);
    pthread_join(threads[1],NULL);


    sum_total = sum1+sum;

    printf("The sum calculated on the threads is %f", sum_total);


    return (EXIT_SUCCESS);
}

关于在 C 中更改线程中的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26758766/

相关文章:

c++ - C++中的变量和引用之间有什么区别?

c - 在 C 中 inotify 文件

c - 如何用 C 表示货币或金钱

c - 按住另一个按钮时,XGrabButton 不会捕获点击

mysql - 如何将变量传递给 IN 子句?

C 链表临时变量

c++ - 从 C++ 到 Pro *C 的控制转换期间的段错误

Python 多处理类型错误 : can't pickle generator objects

c - 变量和多线程的奇怪问题

c++ - 无法获取 std::mutex 来正确保护线程访问