include stdafx include pthread include stdlib include stdio double dou

 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
75
76
77
78
79
80
81
#include "stdafx.h"
#include "pthread.h"
#include <stdlib.h>
#include <stdio.h>
double a=0.0;
double b=1.0;
int n=10;
double total=0.0;
pthread_mutex_t total_mutex = PTHREAD_MUTEX_INITIALIZER;
int p;
double integrate (double a, double b, int n)
{
double res;
double h;
int i;
h=(b-a)/n;
res = 0.5*(a+b)*h;
for (i=1;i<n;i++)
res+=(a+i*h)*h;
return res;
}
void * process_function (void * pa)
{int my_rank = (int) pa;
double len = (b-a)/n;
int local_n = n/p;
double local_a=a+my_rank*len;
double local_b = local_a+len;
double integral;
integral = integrate (local_a,local_b,local_n);
pthread_mutex_lock (&total_mutex);
total+=integral;
pthread_mutex_unlock (&total_mutex);
return 0;
}
int _tmain(int argc, char* argv[])
{
pthread_t * threads;
int i;
if(argc!=2)
{
printf ("Usage: %s <instances>\n", argv[0]);
return 1 ;
}
p = (int) strtol (argv[1],0,10);
if (!(threads = (pthread_t*) malloc (p*sizeof(pthread_t))))
{ fprintf (stderr, "NEM\n");
return 1;
}
for (i=0;i<p;i++)
{
if (pthread_create (threads +i, 0 , process_function, (void*)i))
{fprintf (stderr, "thread #%d!\n",i);
return 2;
}
}
for (i=0;i<p;i++)
if (pthread_join (threads[i],0))
fprintf (stderr, "wait thread #d!\n" ,i);
free (threads);
printf ("Integral from %lf to %lf = %.18lf\n", a ,b,total);
return 0;
}