Advertisement
Guest User

Untitled

a guest
Oct 31st, 2014
149
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.39 KB | None | 0 0
  1. #include <iostream>
  2. #include <thread>
  3. using namespace std;
  4.  
  5. const int processes = 5;
  6. int ticket[processes] = {0,0,0,0,0};
  7. int entering[processes] = {0,0,0,0,0};
  8.  
  9. int max(int ticket2[]) {
  10.     // TODO Auto-generated method stub
  11.  
  12.      int max = 10000;
  13.      for(int i = 0; i < processes;i++){          
  14.          if(ticket2[i]>max)
  15.              max=ticket2[i];       
  16.      }
  17.     return max+1;
  18. }
  19. void lock(int pid){
  20.     entering[pid]=1;
  21.    
  22.     ticket[pid] = max(ticket);    
  23.    
  24.     entering[pid]=0;
  25.    
  26.      for(int i = 0; i < processes; ++i)
  27.      {
  28.          if(i != pid)
  29.          {
  30.              while(entering[i] == 1){} //wait while other thread picks a ticket
  31.              while(ticket[i] != 0 && (ticket[pid] > ticket[i] ||
  32.                  ticket[pid] == ticket[i] && pid > 1)){}
  33.              
  34.          }
  35.      }
  36. }
  37.  
  38. void unlock(int pid){
  39.     ticket[pid]= 0;
  40. }
  41. void nonCriticalSection(int id) {
  42.         // TODO Auto-generated method stub
  43.         cout << "Process : " << id << " is in its non-critical section" << endl;
  44.     }
  45.  
  46. void criticalSection(int id) {
  47.     cout << "Process : " << id << " is in its critical section"<<endl;
  48.     this_thread::sleep_for(std::chrono::seconds(5));
  49. }
  50.  
  51. void CS(int id){
  52.     int m_id=id;
  53.    
  54.     while(true){   
  55.             lock(id);
  56.             criticalSection(m_id);
  57.             unlock(id);
  58.             nonCriticalSection(m_id);
  59.        
  60.     }
  61. }
  62. int main(){
  63.     thread t0(CS,0);
  64.     thread t1(CS,1);
  65.     thread t2(CS,2);
  66.     thread t3(CS,3);
  67.     thread t4(CS,4);
  68.        
  69.  
  70.     system("PAUSE");
  71. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement