Gerard-Meier

Sushi bar problem

May 15th, 2012
99
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.73 KB | None | 0 0
  1. #include <cstdlib>
  2. #include <pthread.h>
  3. #include <iostream>
  4. #include "Semphore.h"
  5. #include <assert.h>
  6.  
  7. using namespace std;
  8.  
  9. Semaphore* tableMutex;
  10. Semaphore* waiting;
  11.  
  12. int table;
  13. int inQueue;
  14. bool doPrint = true;
  15.  
  16.  
  17. void guest(void *) {
  18.     assert(table <= 5);
  19.  
  20.     tableMutex->wait();
  21.     if(table == 5) {
  22.         if(doPrint) printf("[Sitting: %i/5, waiting: %02d] Table full, queuing for empty table. \n", table, inQueue);
  23.         inQueue++;
  24.  
  25.         tableMutex->signal();
  26.         waiting->wait();
  27.         tableMutex->wait();
  28.        
  29.     } else {
  30.         ++table;
  31.     }
  32.    
  33.    
  34.     tableMutex->signal();
  35.  
  36.  
  37.     if(doPrint) printf("[Sitting: %i/5, waiting: %02d] Someone took a seat. Nomnomnomnom. \n", table, inQueue);
  38.     assert(table <= 5);
  39.  
  40.     // Nomnomnom
  41.  
  42.     tableMutex->wait();
  43.     --table;
  44.     if(doPrint) printf("[Sitting: %i/5, waiting: %02d] Someone finished their meal! \n", table, inQueue);
  45.     if(table <= 0) {
  46.         if(doPrint) printf("[Sitting: %i/5, waiting: %02d] Table empty, signalling up to 5 people. \n", table, inQueue);
  47.  
  48.         // Table is empty, signal 5 guests.
  49.         for(int i = 0; i < 5; ++i) {
  50.             waiting->signal();
  51.         }
  52.  
  53.         table   += min(5, inQueue);
  54.         inQueue  = max(0, inQueue -= 5);
  55.     }
  56.  
  57.     assert(table <= 5);
  58.  
  59.     tableMutex->signal();
  60. }
  61.  
  62.  
  63. int main(int argc, char** argv) {
  64.     tableMutex = new Semaphore(1);
  65.     waiting    = new Semaphore(0);
  66.    
  67.     table   = 0; // Table is empty.
  68.     inQueue = 0; // Queue is empty.
  69.  
  70.     // Summon some guests:
  71.     for(int i = 0; i < 20; ++i) {
  72.         pthread_t _threadIndex;
  73.         pthread_create(&_threadIndex, 0, (void *(*) (void *))&guest, NULL);
  74.     }
  75.  
  76.     return cin.get();
  77. }
Advertisement
Add Comment
Please, Sign In to add comment