/* Copyright (C) 2009 by Mattia Monga */ /* $Id$ */ #include #include #include #include #include #include void down(sem_t *s){ if (sem_wait(s) < 0){ perror("Errore semaforo (down)"); exit(1); } } void up(sem_t *s){ if (sem_post(s) < 0){ perror("Errore semaforo (up)"); exit(1); } } int shared = 0; pthread_t p1, p2; sem_t ss; void* run(void* s){ while (down(&ss), shared < 10) { sleep(1); printf("Processo thread (%p). s = %d\n", pthread_self(), shared); if (!(shared < 10)){ printf("Corsa critica!!!!\n"); abort(); } shared += 1; up(&ss); pthread_yield(); } up(&ss); return NULL; } int main(void){ if (sem_init(&ss, 0 /* thread local semaphore */, 1 /* init value */ ) < 0){ perror("Errore semaforo"); exit(1); } pthread_create(&p1, NULL, run, NULL); pthread_create(&p2, NULL, run, NULL); pthread_join(p1, NULL); pthread_join(p2, NULL); sem_destroy(&ss); return 0; } /* Local Variables: */ /* compile-command: "make -k " */ /* End: */