1
\$\begingroup\$

I need feedback on my code for following statement, am I on right path?

Problem statement:

  1. Implement a semaphore class that has a private int and three public methods: init, wait and signal. The wait and signal methods should behave as expected from a semaphore and must use Peterson's N process algorithm in their implementation.

  2. Write a program that creates 5 threads that concurrently update the value of a shared integer and use an object of semaphore class created in part a) to ensure the correctness of the concurrent updates.

Here is my working program:

#include <iostream>
#include <pthread.h>

using namespace std;

pthread_mutex_t mid;                   //muted id
int shared=0;                           //global shared variable
class semaphore {
   int counter;
public:
   semaphore(){
   }
   void init(){
       counter=1;                     //initialise counter 1 to get first thread access
   }
   void wait(){
       pthread_mutex_lock(&mid);         //lock the mutex here
       while(1){
           if(counter>0){             //check for counter value
               counter--;             //decrement counter
               break;                   //break the loop
           }

       }
       pthread_mutex_unlock(&mid);       //unlock mutex here
   }
   void signal(){
       pthread_mutex_lock(&mid);       //lock the mutex here
           counter++;                   //increment counter
           pthread_mutex_unlock(&mid);   //unlock mutex here
       }

};
semaphore sm;
void* fun(void* id)
{
   sm.wait();                           //call semaphore wait
   shared++;                           //increment shared variable
   cout<<"Inside thread "<<shared<<endl;
   sm.signal();                       //call signal to semaphore
}


int main() {

   pthread_t id[5];                   //thread ids for 5 threads
   sm.init();
   int i;
   for(i=0;i<5;i++)                   //create 5 threads
   pthread_create(&id[i],NULL,fun,NULL);
   for(i=0;i<5;i++)
   pthread_join(id[i],NULL);           //join 5 threads to complete their task
   cout<<"Outside thread "<<shared<<endl;//final value of shared variable
   return 0;
}
\$\endgroup\$
  • 4
    \$\begingroup\$ I don't see Peterson's algorithm anywhere. \$\endgroup\$ – JS1 Dec 1 '17 at 5:21
  • \$\begingroup\$ thats because I dont know how to implement it can you help me with the code? \$\endgroup\$ – June Dec 1 '17 at 14:44
  • \$\begingroup\$ This is not the right place for asking questions about unwritten code. But wikipedia pretty much explains it all. \$\endgroup\$ – JS1 Dec 2 '17 at 5:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.