在C中更改线程中的变量
我知道这是非常基本的,但我很难理解,英语不是我的母语,所以很抱歉有任何打字错误 我有一个程序,它必须使用两个线程来计算前999999个数字的平方根之和。其中一条线必须将两条线相加,另一条线必须计算赔率。我的问题是,当更改线程中每个和的变量时,我总是会出现两个错误,甚至无法编译。我对指针很陌生,所以我猜问题就在那里在C中更改线程中的变量,c,multithreading,variables,pointers,C,Multithreading,Variables,Pointers,我知道这是非常基本的,但我很难理解,英语不是我的母语,所以很抱歉有任何打字错误 我有一个程序,它必须使用两个线程来计算前999999个数字的平方根之和。其中一条线必须将两条线相加,另一条线必须计算赔率。我的问题是,当更改线程中每个和的变量时,我总是会出现两个错误,甚至无法编译。我对指针很陌生,所以我猜问题就在那里 #include <stdio.h> #include <stdlib.h> #include <pthread.h> #include <m
#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);
}
#包括
#包括
#包括
#包括
无效*计算对(无效*总和){
int i;
对于(i=0;i将*sum+=sqrt(i);
更改为*(double*)sum+=sqrt(i);
您不能取消引用void*
。在取消引用之前,将Typecast转换为所需类型首先,您没有将void*转换为double*。第二个错误是将参数传递给pthread\u 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);
}
#包括
#包括
#包括
#包括
无效*计算对(无效*总和){
int i;
双*b;
b=(双*)和;
对于(i=0;iYou说您有一个错误,但它看起来像是一个警告。?您有编译错误或警告吗?有什么理由不声明要使用的函数double*sum1
?@LasseV.Karlsen原因是:很好的理由,我收回我的评论:)这些行:sum1+=sqrt(a);应该是:*(double)sum1+=sqrt(a);谢谢!这有助于修复程序并使我了解问题。