Last active
August 29, 2015 14:20
-
-
Save sigorilla/7c6fb9101e6ae66c2592 to your computer and use it in GitHub Desktop.
Pthread integral. To build enter command: > make
This file contains hidden or 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 <sys/types.h> | |
| #include <sys/stat.h> | |
| #include <stdlib.h> | |
| #include <stdio.h> | |
| #include <fcntl.h> | |
| #include <unistd.h> | |
| #include <string.h> | |
| #include <errno.h> | |
| #include <pthread.h> | |
| int i, n; | |
| // Max n = 10000 | |
| double a, b; | |
| double result = 0.0, length; | |
| double *from_this; | |
| /* Your function */ | |
| double f(double x) { | |
| return 1 / ( x * x ); | |
| } | |
| /* Thread */ | |
| void *integrate(void *arg) { | |
| double local = *(double *)arg; | |
| double u; | |
| /* Middle of [a;b] */ | |
| u = local + length/2; | |
| result += f(u)*length; | |
| pthread_exit(NULL); | |
| } | |
| int main(int argc, char **argv) { | |
| if (argc != 4) { | |
| printf("Wrong numbers of parameters. USAGE: a b n\n"); | |
| exit(-1); | |
| } | |
| a = atof(argv[1]); | |
| b = atof(argv[2]); | |
| n = atoi(argv[3]); | |
| /* Length division */ | |
| length = ( b - a ) / n; | |
| pthread_t tid[n]; | |
| from_this = ( double * ) malloc( n * sizeof( double ) ); | |
| for ( i = 0; i < n; i++ ) { | |
| from_this[ i ] = a + i * length; | |
| if ( pthread_create(&tid[i], NULL, integrate, (void *) &from_this[i]) ) { | |
| printf("Error of creating thread: %s\n", strerror(errno)); | |
| exit(-1); | |
| } | |
| } | |
| for ( i = 0; i < n; i++ ) { | |
| if ( pthread_join(tid[i], NULL) ) { | |
| printf("Error of joining thread %d: %s\n", i, strerror(errno)); | |
| exit(-1); | |
| } | |
| } | |
| double out = result; | |
| printf("Integral equals to %lf.\n", out); | |
| free(from_this); | |
| return 0; | |
| } |
This file contains hidden or 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
| CC=gcc | |
| CFLAGS=-Wall -ggdb | |
| all: Integral | |
| Integral: main.c | |
| $(CC) $(CFLAGS) -o integral main.c -lpthread |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment