#include #include #include #include #include #define K 3 #define N 10 #define JUG 1 #define SEVER 2 #define NEODREDJENO 0 pthread_mutex_t MOST = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t CONDS = PTHREAD_COND_INITIALIZER; pthread_cond_t CONDJ = PTHREAD_COND_INITIALIZER; int smer = NEODREDJENO; int cekaJUG=0; int cekaSEVER=0; int prelaziJUG = 0; int prelaziSEVER = 0; int k = 0; void *autoJUG(void *x) { sleep(rand() % 5); long id = (long)x; pthread_mutex_lock(&MOST); cekaJUG++; while(smer == SEVER || (smer==JUG && k >= K && cekaSEVER!=0)) { pthread_cond_wait(&CONDJ, &MOST); } cekaJUG--; prelaziJUG++; k ++; smer = JUG; pthread_mutex_unlock(&MOST); printf("Automobil %ld prelazi most sa juzne strane!\n", id); fflush(stdin); sleep(1); pthread_mutex_lock(&MOST); prelaziJUG --; if(k >= K && cekaSEVER || ( cekaJUG == 0 && prelaziJUG == 0 && cekaSEVER )) { k=0; smer = SEVER; pthread_cond_broadcast(&CONDS); } pthread_mutex_unlock(&MOST); return NULL; } void *autoSEVER(void *x) { sleep(rand() % 5); long id = (long)x; pthread_mutex_lock(&MOST); cekaSEVER++; while(smer == JUG || (smer==SEVER && k >= K && cekaJUG!=0)) { pthread_cond_wait(&CONDS, &MOST); } cekaSEVER--; prelaziSEVER++; k ++; smer = SEVER; pthread_mutex_unlock(&MOST); printf("Automobil %ld prelazi most sa severne strane!\n", id); sleep(1); pthread_mutex_lock(&MOST); prelaziSEVER --; if(k >= K && cekaJUG || ( cekaSEVER == 0 && prelaziSEVER == 0 && cekaJUG )) { k=0; smer = JUG; pthread_cond_broadcast(&CONDJ); } pthread_mutex_unlock(&MOST); return NULL; } int main() { pthread_t aJUG[N]; pthread_t aSEVER[N]; for(long i=0;i