Created
April 30, 2013 21:02
-
-
Save dmitru/5491932 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <pthread.h> | |
#include <stdio.h> | |
#include <stdlib.h> | |
struct thr_data{ | |
double b; | |
double e; | |
double step; | |
double count; | |
}; | |
double func(double arg) | |
{ | |
double res; | |
res = 1.0; | |
return res; | |
} | |
void* thr_routine(void* n) | |
{ | |
struct thr_data* cur_data = (struct thr_data*)(n); | |
printf("New thread: b=%f, e=%f\n", cur_data->b, cur_data->e); | |
double h = 0.0; | |
double i; | |
for (i = cur_data->b; i < cur_data->e; i+=cur_data->step) { | |
h += func(i+cur_data->step/2); | |
} | |
printf("h = %f\n", h); | |
cur_data->count += h*cur_data->step; | |
return (void*)(&cur_data->count); | |
} | |
/* argv: [1][2] - [a,b], [3]- step,[4] - num of threads*/ | |
int main(int agrc, char* argv[]) | |
{ //a,b - double!!! | |
double a = atof(argv[1]); | |
double b = atof(argv[2]); | |
double s = atof(argv[3]); | |
int n = atoi(argv[4]); | |
double len = (b-a)/n; | |
pthread_t* my_tr = (pthread_t*)malloc(n*sizeof(pthread_t)); | |
struct thr_data* thr_arr = (struct thr_data*)malloc(n*sizeof(struct thr_data)); | |
int i; | |
for (i = 0; i < n; i++) { | |
b = a+len; | |
thr_arr[i].b = a; | |
thr_arr[i].e = b; | |
a = b; | |
thr_arr[i].step = s; | |
thr_arr[i].count = 0.0; | |
printf("Struct %d: beg %f end %f step %f\n", i, thr_arr[i].b, thr_arr[i].e, thr_arr[i].step); | |
} | |
for (i = 0; i<n; i++) { | |
int pthread_create_status; | |
pthread_create_status = pthread_create(&my_tr[i], NULL, thr_routine, (void*)(&thr_arr[i])); | |
} | |
double sum = 0.0; | |
int pthread_join_status; | |
for(i = 0; i < n; i++) { | |
void* res; | |
pthread_join_status = pthread_join(my_tr[i], &res); | |
printf("%f\n", *(double*)(res)); | |
sum += *(double*)(res); | |
} | |
printf("=====================%f\n", sum); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment