Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <thread>
- using namespace std;
- const int processes = 5;
- int ticket[processes] = {0,0,0,0,0};
- int entering[processes] = {0,0,0,0,0};
- int max(int ticket2[]) {
- // TODO Auto-generated method stub
- int max = 10000;
- for(int i = 0; i < processes;i++){
- if(ticket2[i]>max)
- max=ticket2[i];
- }
- return max+1;
- }
- void lock(int pid){
- entering[pid]=1;
- ticket[pid] = max(ticket);
- entering[pid]=0;
- for(int i = 0; i < processes; ++i)
- {
- if(i != pid)
- {
- while(entering[i] == 1){} //wait while other thread picks a ticket
- while(ticket[i] != 0 && (ticket[pid] > ticket[i] ||
- ticket[pid] == ticket[i] && pid > 1)){}
- }
- }
- }
- void unlock(int pid){
- ticket[pid]= 0;
- }
- void nonCriticalSection(int id) {
- // TODO Auto-generated method stub
- cout << "Process : " << id << " is in its non-critical section" << endl;
- }
- void criticalSection(int id) {
- cout << "Process : " << id << " is in its critical section"<<endl;
- this_thread::sleep_for(std::chrono::seconds(5));
- }
- void CS(int id){
- int m_id=id;
- while(true){
- lock(id);
- criticalSection(m_id);
- unlock(id);
- nonCriticalSection(m_id);
- }
- }
- int main(){
- thread t0(CS,0);
- thread t1(CS,1);
- thread t2(CS,2);
- thread t3(CS,3);
- thread t4(CS,4);
- system("PAUSE");
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement