#include #include #include #include // Ressources disponible int M = 4; // Mutex static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t cond = PTHREAD_COND_INITIALIZER; void prendre_ressource(int rsc){ if (pthread_mutex_lock(&mutex)) exit(-1); while (rsc > M) pthread_cond_wait(&cond, &mutex); if (M - rsc >= 0) M -= rsc; else exit(1); pthread_mutex_unlock(&mutex); } void liberer_ressource(int rsc){ if (pthread_mutex_lock(&mutex)) exit(-1); M += rsc; pthread_cond_broadcast(&cond); pthread_mutex_unlock(&mutex); } void * fn_thread (void * p_int) { int rsc = *(int *) p_int; printf("Thread en attente pour %d ressource(s)...\n", rsc); prendre_ressource(rsc); printf("Thread a pris %d ressource(s)...\n", rsc); sleep(rsc); printf("%d ressource(s) utilisée(s) et rendue(s)...\n", rsc); liberer_ressource(rsc); printf("Thread (à %d rsc) fini...\n", rsc); pthread_exit(0); } int main () { pthread_t p1; pthread_t p2; pthread_t p3; int rsc1 = 3; int rsc2 = 2; int rsc3 = 1; pthread_create (& p1, NULL, fn_thread, (void *) &rsc1); pthread_create (& p2, NULL, fn_thread, (void *) &rsc2); pthread_create (& p3, NULL, fn_thread, (void *) &rsc3); pthread_join(p1, NULL); pthread_join(p2, NULL); pthread_join(p3, NULL); return 0; }