Created
May 22, 2013 08:53
-
-
Save appplemac/5626181 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<stdio.h> | |
#include<stdlib.h> | |
#include<string.h> | |
#include <pthread.h> | |
#include <sys/types.h> | |
#include <unistd.h> | |
#define MAX 10000 | |
#define NTHREADS 10 | |
struct infojob { | |
int ini; /* posición inicial */ | |
int fin; /* posición final */ | |
int res; /* resultado parcial */ | |
}; | |
int globalvector[MAX]; | |
struct infojob jobs_info[NTHREADS]; | |
pthread_mutex_t mutex; | |
void* sum(void* pointer) { | |
struct infojob* job = (struct infojob*)pointer; | |
int i; | |
for (i = job->ini; i <= job->fin; ++i) { | |
pthread_mutex_lock(&mutex); | |
job->res += globalvector[i]; | |
pthread_mutex_unlock(&mutex); | |
} | |
pthread_exit(0); | |
} | |
int main() | |
{ | |
int i; | |
int suma = 0; | |
char buf[100]; | |
pthread_mutex_init(&mutex, NULL); | |
/* init global vector */ | |
for (i=0; i< MAX; i++) { | |
globalvector[i] = i; | |
} | |
pthread_t thr[NTHREADS]; | |
for (i=0; i<NTHREADS; ++i) { | |
jobs_info[i].ini = (MAX/NTHREADS)*i; | |
jobs_info[i].fin = (MAX/NTHREADS)*(i+1)-1; | |
jobs_info[i].res = 0; | |
pthread_create(&thr[i], NULL, &sum, &jobs_info[i]); | |
} | |
for (i=0; i<NTHREADS; i++) { | |
pthread_join(thr[i], NULL); | |
suma += jobs_info[i].res; | |
} | |
sprintf (buf, "El resultado de la suma es %d\n", suma); | |
write (1, buf, strlen(buf)); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment