include pthread include iostream include stdlib include cmath double s

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
#include <pthread.h>
#include <iostream>
#include <stdlib.h>
#include <cmath>
double seriesLeibnitz(long start, long endN)
{
double a = 0.;
for (int i = start + 1; i <= endN; i++)
a += (double)(pow(-1, i) / (1 + 2.0 * i));
return a;
}
struct Data{
long start;
long endN;
};
static void *func(void *lpParam)
{
struct Data dt = *((struct Data *)lpParam);
double* result = (double*) malloc(sizeof(double));
*result = seriesLeibnitz(dt.start, dt.endN);
return result;
}
int main (int argc, char *argv[])
{
const int N = 4;
long iterations = 10000000;
pthread_t *th = new pthread_t[N];
Data *dat = new Data[N];
for (int i = 0; i < N; i++){
dat[i].start = iterations / N * i;
dat[i].endN = iterations / N * i + iterations / N;
pthread_create(&th[i], NULL, func, &dat[i]);
}
double dbl;
void *t;
double S = 1;
for (int i = 0; i < N; i++){
pthread_join(th[i], (void**)&t);
dbl = *(double*) t;
S +=dbl;
}
S *= 4;
std::cout << "Result: " << S << std::endl;
free(th);
}