C - Linux - Pthreads and Semaphore -


i having trouble trying implement semaphores pthreads. scenario trying program rats in maze. rats threads , maze consists of rooms connected each other. rats have traverse through each room each room having different capacity , wait time before rat can move on. able implement while loop , let threads sit , spin while waiting spot free need achieve objective semaphores. here's have:

sem_t psem, csem;  void enterroom(int irat, int iroom) {      time_t currenttime;      currenttime = time(null);      roomvb[iroom][irat].tentry = currenttime - starttime;     roomvb[iroom][irat].irat = irat;     visitorcount[iroom]++;     sleep(roomarray[iroom].delay); }  void leaveroom(int irat, int iroom) {      time_t currenttime;      currenttime = time(null);      visitorcount[iroom]--;     roomvb[iroom][irat].tdep = currenttime - starttime; }  void *rat(void *ratid) {      if (sem_init(&csem, 0, 0) < 0) {         perror("sem_init");         exit(1);     }      int id;      id = (int)ratid;      int i;      (i = 0; < numofrooms; i++) {      /*while (visitorcount[i] >= roomarray[i].capacity) {      }*/      if (sem_init(&psem, 0, roomarray[i].capacity) < 0) {         perror("sem_init");         exit(1);         }       sem_wait(&psem);     enterroom(id, i);     sem_post(&csem);      sem_wait(&csem);     leaveroom(id, i);     sem_post(&psem);      }      return null;  } 

as can see commented out while loop. had incorporate additional information time it takes rat travel through rooms in 2d array.

error result:

rat 0 completed maze in 5 seconds. rat 1 completed maze in 5 seconds. rat 2 completed maze in 5 seconds. room 0 [3 1]: 0 0 1; 1 0 1; 2 0 1;  room 1 [2 2]: 0 1 3; 1 1 3; 2 1 3;  room 2 [1 2]: 0 3 5; 1 3 5; 2 3 5;  total traversal time: 15 seconds, compared ideal time: 15 seconds. 

correct result (achieved loop):

rat 0 completed maze in 7 seconds. rat 1 completed maze in 5 seconds. rat 2 completed maze in 9 seconds. room 0 [3 1]: 0 0 1; 1 0 1; 2 0 1;  room 1 [2 2]: 0 1 3; 1 1 3; 2 3 5;  room 2 [1 2]: 0 5 7; 1 3 5; 2 7 9;  total traversal time: 21 seconds, compared ideal time: 15 seconds. 

i assume need 2 semaphores producer semaphore being set n - capacity of each room. ideas how fix works should?

you can't have each thread re-initialise same 2 shared semaphores simultaneously. semaphores need initialised up-front, before rats start running.

the easiest way solve have 1 semaphore each room, initialised capacity of room (store sempahore in roomarray element room). then, have rat wait on semaphore when enters room, , post semaphore when exits room.


Comments

Popular posts from this blog

1111. appearing after print sequence - php -

java - WARN : org.springframework.web.servlet.PageNotFound - No mapping found for HTTP request with URI [/board/] in DispatcherServlet with name 'appServlet' -

Ruby on Rails, ActiveRecord, Postgres, UTF-8 and ASCII-8BIT encodings -