/* * Tentativa de implementar o algoritmo de Dekker para N theads. */ #include #include #include #include #define N 5 enum estado {passive, requesting, in_cs}; volatile int s = 0; /* Variável compartilhada */ volatile int vez = 1; volatile enum estado interesse[N]; int existe_outra_in_cs(int thr_id) { int i; for (i = 0; i < N; i++) if (i != thr_id && interesse[i] == in_cs) return 1; return 0; } void* f_thread(void *v) { int thr_id = *(int*)v; int i, vez_local; for (i = 0; i < 5; i++) { do { interesse[thr_id] = requesting; if (thr_id == 0) sleep(50); vez_local = vez; while (vez_local != thr_id) if (interesse[vez_local] != passive) vez_local = vez; else vez_local = (vez_local + 1) % N; interesse[thr_id] = in_cs; } while (existe_outra_in_cs(thr_id)); vez = thr_id; s = thr_id; printf("Thread %d, s = %d.\n", thr_id, s); vez = (thr_id+1) % N; interesse[thr_id] = passive; sleep(1); } return NULL; } int main() { pthread_t thr[N]; int id[N], i; for (i = 0; i < N; i++) interesse[i] = passive; for (i = 0; i < N; i++) { id[i] = i; pthread_create(&thr[i], NULL, f_thread, &id[i]); } for (i = 0; i < N; i++) pthread_join(thr[i], NULL); return 0; }