Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- * Miguel Albergaria
- * 1170551
- *
- */
- #include <pthread.h>
- #include <stdio.h>
- #include <string.h>
- #include <stdlib.h>
- #include <unistd.h>
- #define NUM_THREADS 100
- pthread_mutex_t mutexVotacao = PTHREAD_MUTEX_INITIALIZER;
- pthread_mutex_t mutexVotar = PTHREAD_MUTEX_INITIALIZER;
- pthread_mutex_t mutexContar = PTHREAD_MUTEX_INITIALIZER;
- pthread_cond_t condVotacaoAbre = PTHREAD_COND_INITIALIZER;
- pthread_cond_t condVotacaoFecha = PTHREAD_COND_INITIALIZER;
- int flag;
- int fechou;
- char texto[100] = "Texto da votacao";
- char votos[NUM_THREADS];
- int numVotos;
- int sim;
- int value;
- void *socioVota(void *arg) {
- pthread_mutex_lock(&mutexVotacao);
- if (fechou == 1) {
- printf("Socio não votou (Votacao está fechada)!\n");
- pthread_mutex_unlock(&mutexVotacao);
- value = 0;
- pthread_exit((void *) &value);
- }
- pthread_mutex_unlock(&mutexVotacao);
- time_t t;
- srand ((unsigned) time (&t));
- int *ptr = (int *) arg;
- int index = *ptr;
- int votoInt = rand() % 2;
- char voto;
- pthread_mutex_lock(&mutexContar);
- if (votoInt) {
- voto = 'S';
- sim++;
- } else {
- voto = 'N';
- }
- numVotos++;
- pthread_mutex_unlock(&mutexContar);
- printf("%s\n", texto);
- printf("Voto (%d): %c\n", index, voto);
- pthread_mutex_lock(&mutexVotar);
- votos[index] = voto;
- pthread_mutex_unlock(&mutexVotar);
- value = 1;
- pthread_exit((void *) &value);
- }
- void *simularVotos(void *arg) {
- pthread_mutex_lock(&mutexVotacao);
- while (flag == 0) {
- pthread_cond_wait(&condVotacaoAbre, &mutexVotacao);
- }
- flag = 0;
- pthread_mutex_unlock(&mutexVotacao);
- printf("Votacoes abertas...\n\n");
- pthread_t threads[NUM_THREADS];
- int pos[NUM_THREADS];
- int i;
- for (i = 0; i < NUM_THREADS; i++) {
- pos[i] = i;
- if (pthread_create(&threads[i], NULL, socioVota, &pos[i]) != 0) {
- printf("Erro no pthread_create()!\n");
- exit(1);
- }
- /*void *ret = NULL;
- if(pthread_join(threads[i], &ret) != 0){
- perror("Erro a terminar thread...");
- exit(1);
- }
- int v = *((int *) arg);
- printf("V: %d\n", v);*/
- sleep(2);
- }
- pthread_exit(NULL);
- }
- int main() {
- flag = 0;
- fechou = 0;
- numVotos = 0;
- sim = 0;
- value = 0;
- pthread_t thread;
- if (pthread_create(&thread, NULL, simularVotos, NULL) != 0) {
- printf("Erro no pthread_create()!\n");
- exit(1);
- }
- pthread_mutex_lock(&mutexVotacao);
- flag = 1;
- pthread_cond_broadcast(&condVotacaoAbre);
- pthread_mutex_unlock(&mutexVotacao);
- sleep(120);
- pthread_mutex_lock(&mutexVotacao);
- fechou = 1;
- pthread_mutex_unlock(&mutexVotacao);
- if(pthread_join(thread, NULL) != 0){
- perror("Erro a terminar thread...");
- exit(1);
- }
- printf("\nVotos: %d de %d\n", numVotos, NUM_THREADS);
- printf("Votos a favor: %d\n", sim);
- printf("Votos contra: %d\n", numVotos - sim);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement