I need to feedback on my code for following statement, am I on right path?
Problem statement:
-
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.
-
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; }