我实际上对我的代码没有问题,但是在我第一次提交时我得到了0.而TA只是说我的程序是非同时运行的(是的,这很有趣,我也不知道我是如何管理的使一个线程程序顺序或者:))所以,我在我的代码中进行了一些更改以进行重新评估。它提供了正确的输出,但我不确定它的并发性。我不想再次获得0所以请你告诉我这次我是不是这样做:)提前致谢。
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <pthread.h>
#include <time.h>
#include "function.h"
double sum = 0.0;
typedef struct thread { //constructing struct for passing arguments to threads
double delta;
double interval;
int low;
int K2;
int threadNo;
} ThreadArgs;
void *thr_integral(void *arg){
ThreadArgs *newOne = (ThreadArgs*) arg;
double temp = 0.0;
int i = newOne->threadNo;
for(int k = 0; k < newOne->K2 ; k++){
double a = newOne->low + (newOne->interval*i) + (k*newOne->delta); //lower bound of trapezoid
double b = newOne->low + (newOne->interval*i) + ((k+1)*newOne->delta); //upper bound of trapezoid
double y = compute_f(a);
double z = compute_f(b);
temp += ((y+z)/2)*(b-a);
}
sum += temp;
pthread_exit(0);
}
int main(int argc, char *argv[])
{
int L = atoi(argv[1]); //reading values
int U = atoi(argv[2]); //reading values
int K = atoi(argv[3]); //reading values
int N = atoi(argv[4]); //reading values
if(N <= 0 || N > 1000){
printf("Invalid arguments! N can be at most 100 and at least 1.\n ");
return 0;
}
int dif = U-L;
double inter = (double) dif / (double) N;
double deltaX = inter / (double) K;
int i;
ThreadArgs *data = (ThreadArgs*) malloc(N * sizeof(ThreadArgs));
for(i = 0; i < N; i++){
data[i].delta = deltaX;
data[i].interval = inter;
data[i].low = L;
data[i].K2 = K;
data[i].threadNo = i;
}
pthread_t *thrs = (pthread_t*) malloc(N * sizeof(pthread_t));
for(i = 0; i < N; i++)
pthread_create(&thrs[i], NULL, &thr_integral, (void*) &data[i]);
for (i = 0; i<N; i++)
pthread_join(thrs[i], NULL);
printf("%lf", sum);
printf("\n");
pthread_exit(NULL);
}