This repository has been archived by the owner on Apr 22, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
pthread.c
74 lines (59 loc) · 1.72 KB
/
pthread.c
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
#include <stdio.h>
#include <assert.h>
#include <stdlib.h>
#include <pthread.h>
#include <math.h>
#include <sys/time.h>
typedef struct _thread_param
{
long start, end;
double sum;
}ThreadParameter;
const double PI = 3.1415926535897932;
const long STEP_NUM = 1070596096;
const double STEP_LENGTH = 1.0 / 1070596096;
const int THREAD_NUM = 16;
void *calc(void * p)
{
ThreadParameter * param = (ThreadParameter *)p;
double x;
double sum = 0.0;
for(long i = param->start; i < param->end; i++)
{
x = (i + 0.5) * STEP_LENGTH;
sum += 1.0 / (1.0 + x * x);
}
param->sum = sum;
return NULL;
}
int main()
{
struct timeval startTime;
gettimeofday(&startTime, NULL);
double pi = 0;
pthread_t *threadHandles = (pthread_t *) malloc(sizeof(pthread_t) * THREAD_NUM);
ThreadParameter * paramArray[THREAD_NUM];
printf("\nStart calculating with %d threads...\n", THREAD_NUM);
for (int i = 0; i < THREAD_NUM; i++)
{
ThreadParameter *param = (ThreadParameter *)malloc(sizeof(ThreadParameter));
param->start = i * STEP_NUM / THREAD_NUM;
param->end = param->start + STEP_NUM / THREAD_NUM;
paramArray[i] = param;
pthread_create(&threadHandles[i], NULL, calc, (void *)param);
}
for (int i = 0; i < THREAD_NUM; i++)
pthread_join(threadHandles[i], NULL);
for(int i = 0; i < THREAD_NUM; i++)
{
pi += paramArray[i]->sum;
free(paramArray[i]);
}
pi = STEP_LENGTH * pi * 4;
free(threadHandles);
struct timeval endTime;
gettimeofday(&endTime, NULL);
printf("PI = %.16lf with error %.16lf\nTime elapsed : %lf seconds.\n\n", pi, fabs(pi - PI), (endTime.tv_sec - startTime.tv_sec) + ((double)(endTime.tv_usec - startTime.tv_usec) / 10E6 ));
assert(fabs(pi - PI) <= 0.001);
return 0;
}