/* * Extensão com bug do algoritmo do desempate para 3 threads. */ #include #include #include #include volatile int s = 0; /* Variável compartilhada */ volatile int ultimo = 0; /* Guarda o último identificador de thread */ volatile int interesse[3] = {0, 0, 0}; /* Indica quais threads estão interessadas em entrar na região crítica */ void* f_thread_0(void *v) { int i; for (i = 0; i < 10; i++) { interesse[0] = 1; /* Marca que esta thread está interessada */ ultimo = 0; while (ultimo == 0 && (interesse[1] || interesse[2])) ; s = 0; printf("Thread 0, s = %d.\n", s); interesse[0] = 0; /* Marca que saiu da região crítica */ sleep(1); } return NULL; } void* f_thread_1(void *v) { int i; for (i = 0; i < 10; i++) { interesse[1] = 1; ultimo = 1; while (ultimo == 1 && (interesse[0] || interesse[2])) ; s = 1; printf("Thread 1, s = %d.\n", s); interesse[1] = 0; sleep(1); } return NULL; } void* f_thread_2(void *v) { int i; for (i = 0; i < 10; i++) { interesse[2] = 1; /* Marca que esta thread está interessada */ ultimo = 2; while (ultimo == 2 && (interesse[1] || interesse[0])) ; s = 2; printf("Thread 2, s = %d.\n", s); interesse[2] = 0; /* Marca que saiu da região crítica */ sleep(1); } return NULL; } int main() { pthread_t thr0, thr1, thr2; pthread_create(&thr0, NULL, f_thread_0, NULL); pthread_create(&thr1, NULL, f_thread_1, NULL); pthread_create(&thr2, NULL, f_thread_2, NULL); pthread_join(thr0, NULL); pthread_join(thr1, NULL); pthread_join(thr2, NULL); return 0; }