#include #include #include #include #include #include #include #include "rollercoaster.h" using namespace std; int main (int argc, char **argv) { srand (time (nullptr)); sem_init (&admin,false,1); //The false is a boolean that indicates whether this semaphore is visible to other processes sem_init (&board,false,0); sem_init (&unboard,false,0); sem_init (&car,false,0); id = new int[R]; for (int i=0; i < R; i++) id[i] = i+1; RiderThread = new pthread_t [R]; for (int i=0; i < R; i++) pthread_create (&RiderThread[i],nullptr,rider,&id[i]); pthread_create (&CarThread,nullptr,rollercoaster,nullptr); for (int i=0; i < R; i++) pthread_join (RiderThread[i],nullptr); pthread_join (CarThread,nullptr); delete[] id; delete[] RiderThread; return 0; } void *rollercoaster (void *a) { while (true) { sem_wait (&car); //sem_wait is like P. cout << "Car: driving\n"; sleep (30); cout << "Car: ride over\n"; sem_wait (&admin); sem_post (&unboard); //sem_post is like V. } return nullptr; } void *rider (void *a) { int idnum = *(int *)a; while (true) { sleep (10+rand()%21); //sleep 10-30 seconds sem_wait (&admin); if (nr==C) {nrw++; sem_post (&admin); cout << "Rider "+to_string(idnum)+": Waiting to board\n";sem_wait (&board);} nr++; cout << "Rider "+to_string(idnum)+": Boarding\n"; if (nr==C) {sem_post (&car); sem_post (&admin);} else if (nrw > 0) {nrw--; sem_post (&board);} else sem_post (&admin); sem_wait (&unboard); cout << "Rider "+to_string(idnum)+": Unboarding\n"; nr--; if (nr > 0) sem_post (&unboard); else if (nrw > 0) {nrw--; sem_post (&board);} else sem_post (&admin); } return nullptr; }