Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <pthread.h>
- #include <time.h>
- #include <unistd.h>
- #include <stdlib.h>
- #include <sys/time.h>
- int N;
- int P;
- pthread_mutex_t s = PTHREAD_MUTEX_INITIALIZER;
- int Min = 999;
- int Max = -1;
- int *A;
- void vermatriz(int *m, int modo)
- {
- for (int i = 0; i < N; i++)
- {
- for (int j = 0; j < N; j++)
- printf("%d\t", m[i * N + j]);
- printf("\n");
- }
- }
- void *Funcion_maxmin(void *arg)
- {
- int tid = *(int *)arg;
- int ini = tid * (P);
- int fin = (tid + 1) * (P);
- int min = 999;
- int max = -1;
- for (int i = ini; i < fin; i++)
- {
- for (int j = 0; j < N; j++)
- {
- if (A[i * N + j] < min)
- min = A[i * N + j];
- if (A[i * N + j] > max)
- max = A[i * N + j];
- }
- }
- // se lo pasamos a la variable global
- printf("Soy %d\tmin=%d\tmax=%d\n", tid, min, max);
- pthread_mutex_lock(&s);
- if (min < Min)
- Min = min;
- pthread_mutex_unlock(&s);
- pthread_mutex_lock(&s);
- if (max > Max)
- Max = max;
- pthread_mutex_unlock(&s);
- pthread_exit(NULL); //finalizacion del hilo
- }
- int main(int argc, char *argv[])
- {
- int H = 2; // es un valor por defecto en el caso de que no se
- // introduzca ningun valor por consola.
- //Controla los argumentos al programa
- if ((argc != 3) || ((N = atoi(argv[1])) <= 0) || ((H = atoi(argv[2])) <= 0))
- {
- printf("\nUsar: %s n\n h: cant hilos \n", argv[0]);
- exit(1);
- }
- /*Declarar e inicializaciones*/
- N = atoi(argv[1]); // Inicializa valor de mi arreglo de N elementos
- H = atoi(argv[2]); //incializar valor de hilos
- //calculamos la proporcion
- P = N / H;
- /*Matriz A original*/
- A = (int *)malloc(N * N * sizeof(int));
- for (int i = 0; i < N; i++)
- for (int j = 0; j < N; j++)
- A[i * N + j] = rand()%100+1;
- vermatriz(A, 0);
- //Reservo memoria para el vector de hilos
- pthread_t *tid = malloc(sizeof(pthread_t) * H);
- int *threads_ids = malloc(sizeof(int) * H);
- pthread_mutex_init(&s, NULL); // inicializacion s
- for (int t = 0; t < H; t++)
- {
- threads_ids[t] = t;
- pthread_create(&tid[t], NULL, Funcion_maxmin, (void *)&threads_ids[t]);
- }
- for (int t = 0; t < H; t++)
- pthread_join(tid[t], NULL);
- pthread_mutex_destroy(&s);
- printf("resultado max es: %d \n", Max);
- printf("resultado min es: %d \n", Min);
- /*Matriz A original*/
- free(A);
- return (0);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement