Skip to content

Instantly share code, notes, and snippets.

@bestknighter
Last active November 5, 2018 14:30
Show Gist options
  • Save bestknighter/8e1aa05cc4e329fb02c543a19886f009 to your computer and use it in GitHub Desktop.
Save bestknighter/8e1aa05cc4e329fb02c543a19886f009 to your computer and use it in GitHub Desktop.
Código multiplataforma base para os Estudos Dirigidos de Programação Concorrente (UnB)
/****************************************************************************
* *
* Arquivo EstudoDirigidoX.c criado por Gabriel Barbosa (12/0050935) *
* DESCRICAO DO PROBLEMA *
* Codigo multiplataforma *
* Usar flags -std=c11 -lpthread para compilar para Windows *
* Usar flags -std=c11 -pthread para compilar para Linux *
* *
****************************************************************************/
#ifdef _WIN32
#include <windows.h>
#define SLEEP(ms) Sleep(ms)
#else
#define _BSD_SOURCE
#include <unistd.h>
#define SLEEP(ms) usleep( 1000*(ms) )
#endif
#define RAND_INTERVAL(min, max) ( rand()%( (max) - (min) ) + (min) )
#define RAND_INTERVAL2(mid, rng) ( rand()%( 2 * (rng) ) + (mid) - (rng) )
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <semaphore.h>
#include <time.h>
#define MIN_WAIT 3750 // Tempo minimo em ms
#define MAX_WAIT 6250 // Tempo maximo em ms
#define N_THREADS 10
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
pthread_barrier_t barrier;
sem_t semaphore;
int count = 0;
void* thread0_main( void* arg );
int main( int argc, char* argv[] ) {
pthread_t thread[N_THREADS];
pthread_barrier_init( &barrier, NULL, 2 );
sem_init( &semaphore, 0, 1 );
srand( time(NULL) );
int* arg;
for( int i = 0; i < N_THREADS; i++ ) {
arg = (int*) malloc( sizeof(int) );
*arg = rand();
pthread_create( thread+i, NULL, thread0_main, arg );
}
pthread_join( thread[0], NULL );
return 0;
}
void* thread0_main( void* arg ) {
int myArg = *((int*)arg);
free( arg );
srand( myArg );
SLEEP( RAND_INTERVAL( MIN_WAIT, MAX_WAIT ) );
pthread_exit(0);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment