Skip to content

Instantly share code, notes, and snippets.

@Sutil
Created December 11, 2015 22:50
Show Gist options
  • Select an option

  • Save Sutil/56db845b95f5b27c33e1 to your computer and use it in GitHub Desktop.

Select an option

Save Sutil/56db845b95f5b27c33e1 to your computer and use it in GitHub Desktop.
Barreira em C
#include <stdio.h>
#include <pthread.h>
#include <time.h>
#define NUM_THREADS 5
#define MAX_COUNT 100
pthread_barrier_t barrier;
pthread_t threads[NUM_THREADS];
void* dorme_espera(void *arg){
int retorno, contador, tempo;
int thread_id = (int) arg;
while (contador < MAX_COUNT){
contador += thread_id+1;
usleep(rand() % 100);
}
tempo = 999999;
usleep(tempo);
printf("Thread %d esperando na barreira apos dormir %d mili segundos. Contador com valor: %d\n", thread_id, tempo, contador);
retorno = pthread_barrier_wait(&barrier);
if (retorno != 0 && retorno != PTHREAD_BARRIER_SERIAL_THREAD)
printf("Erro de espera na barreira na thread %d", thread_id);
usleep(100000);
printf("Thread %d terminando\n", thread_id);
}
int main() {
int i;
srand(time(NULL));
if (pthread_barrier_init(&barrier, NULL, NUM_THREADS))
printf("Impossivel criar barreira");
for (i = 0 ; i < NUM_THREADS; i++)
if (pthread_create(&threads[i], NULL, dorme_espera, (void*) i))
printf("Erro na criacao das threads");
for(i = 0; i < NUM_THREADS; i++)
if(pthread_join(threads[i], NULL))
printf("Erro no join");
usleep(100000);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment