Friday 1 April 2016

Posix Semaphore: C++ program

Q: Program to implement a Posix Semaphore

Os: Linux Ubuntu 16.04 LTS
Compiler: g++



Code:



#include<iostream>
#include <semaphore.h>
#include<errno.h>
#include<string.h>
#include<unistd.h>
#include<sys/types.h>
#include<math.h>
using namespace std;
sem_t mutex;
int  counter;
using namespace std;
void *fun(void *X) 
{
 int threadcnt = *((int *) X); 
 cout<<" Thread no. "<<threadcnt<<" waiting to enter in critical section"<<endl;
 cout.flush();
 sem_wait(&mutex);
 cout<<" Thread no. "<<threadcnt<<" is in critical section"<<endl;
 cout<<" Counter = "<<counter<<endl; 
 counter++; 
 cout<<" Updated counter value = "<<counter<<endl;
 cout<<" Thread no. "<<threadcnt<<" exits from critical section"<<endl;
 cout.flush(); 
 sem_post(&mutex);
 cout.flush(); 
 
 return (NULL);
}

int main(int argc, char *argv[])
{
 pthread_t ThreadA,ThreadB, ThreadC;
 
 int  Threadnum[3];

 Threadnum[0] = 1;
 Threadnum[1] = 2;
 Threadnum[2] = 3;
sem_init(&mutex,0,1);
 pthread_create(&ThreadA, NULL, &fun, (void *)&Threadnum[0]);
 pthread_create(&ThreadB,NULL, &fun, (void *)&Threadnum[1]);   
 pthread_create(&ThreadC, NULL, &fun, (void *)&Threadnum[2]);
 
 pthread_join(ThreadA, NULL); 
 pthread_join(ThreadB, NULL);
 pthread_join(ThreadC, NULL);
 
 sem_destroy(&mutex);
 
 return (0);

}

/*OUTPUT
g++ ps.cpp -lpthread
usr@comp:~$ ./a.out
 Thread no. 1 waiting to enter in critical section
 Thread no. 1 is in critical section
 Counter = 0
 Updated counter value = 1
 Thread no. 1 exits from critical section
 Thread no. 2 waiting to enter in critical section
 Thread no. 2 is in critical section
 Counter = 1
 Updated counter value = 2
 Thread no. 2 exits from critical section
 Thread no. 3 waiting to enter in critical section
 Thread no. 3 is in critical section
 Counter = 2
 Updated counter value = 3
 Thread no. 3 exits from critical section
usr@comp:~$ 
*/





No comments:

Post a Comment