manasij7479

Dining Philosophers

Jul 30th, 2012
111
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.66 KB | None | 0 0
  1. #include <iostream>
  2. #include <thread>
  3. #include <mutex>
  4. #include <array>
  5. #include <random>
  6. #include <chrono>
  7. #include <vector>
  8.  
  9. const int nump=5;
  10. class Philosopher
  11. {
  12. public:
  13.     Philosopher(int n_):n(n_)
  14.     {
  15.         chops.first = n;
  16.         chops.second = (n<4)?n+1:0;
  17.         randgen.seed(n);
  18.     };
  19.     void operator()(std::array<std::mutex,nump>& locks)
  20.     {
  21.         while(true)
  22.         {
  23.             std::chrono::milliseconds sleep_time (randgen()%10000),eat_time(randgen()%10000);
  24.             log("Thinking");
  25.             std::this_thread::sleep_for(sleep_time);
  26.            
  27.             bool hungry=true;
  28.             int first,second;
  29.             while(hungry)
  30.             {
  31.                 int choice =randgen()%2;
  32.                 first =chops.first;
  33.                 second = chops.second;
  34.                 if(choice)
  35.                     std::swap(first,second);
  36.  
  37.                 if(locks[first].try_lock())
  38.                     if(locks[second].try_lock())
  39.                         {
  40.                             log("Eating");
  41.                             std::this_thread::sleep_for(eat_time);
  42.                             hungry=false;
  43.                         }
  44.                     else locks[first].unlock();
  45.                 std::this_thread::sleep_for(std::chrono::milliseconds(1));
  46.             }
  47.             locks[first].unlock();
  48.             locks[second].unlock();
  49.            
  50.         }
  51.  
  52.     }
  53.     void log(const std::string& data)
  54.     {
  55.         while(!cout_lock.try_lock())std::this_thread::sleep_for(std::chrono::milliseconds(1));
  56.         std::cout<<"Philosopher "<<n<<" "<<data<<std::endl;
  57.         cout_lock.unlock();
  58.     }
  59. private:
  60.     int n;
  61.     std::pair<int,int> chops;
  62.     std::mt19937 randgen;
  63.     static std::mutex cout_lock;
  64. };
  65. std::mutex Philosopher::cout_lock;
  66. int main()
  67. {
  68.     std::array<std::mutex,nump> chops;
  69.     std::vector<std::thread> threads;
  70.     for(int i=0;i<nump;++i)
  71.         threads.push_back
  72.         (
  73.             std::thread
  74.             (
  75.                 Philosopher(i),
  76.                 std::ref(chops)
  77.             )
  78.         );
  79.     for(auto& t:threads)
  80.         t.join();
  81.     return 0;
  82. }
Advertisement
Add Comment
Please, Sign In to add comment