Multicore Programming – Producer Consumer problem solved by threads (C++)
April 24, 2016
Categorised in: C++ Codes, OOMP Codes
#include <iostream>
#include <stdlib.h>
#include <pthread.h>
#include <semaphore.h>
using namespace std;
pthread_mutex_t status;
sem_t empty,full;
int buffer[50],x,item;
void initialization()
{
sem_init(&empty,1,0);
sem_init(&full,1,50);
pthread_mutex_init(&status,NULL);
x=0;
}
void* producer(void *para)
{
item=rand()%100;
sem_wait(&full); //Producer waits if buffer is full
pthread_mutex_lock(&status); //Lock the status, so that only one thread can access buffer at a time
buffer[x]=item; //producer enters the no. in the buffer
cout<<"\nProducer has producer : "<<buffer[x];
x++;
pthread_mutex_unlock(&status); //Unlocks the buffer
sem_post(&empty);
}
void* consumer(void *para)
{
sem_wait(&empty);//if buffer is empty,consumer waits
pthread_mutex_lock(&status);//Lock the status, so that only one thread can access buffer at a time
x--;
item=buffer[x];//Consumer consumes an element
cout<<"\nConsumer has consumed : "<<buffer[x];
pthread_mutex_unlock(&status);//Unlocks the buffer
sem_post(&full);
}
int main()
{
int n,i,p,c;
initialization();
cout<<"\nEnter how many producers do you want to create : ";
cin>>p;
cout<<"\nEnter how many consumers do you want to create : ";
cin>>c;
pthread_t pid[p],cid;
for(i=0;i<p;i++)
{
pthread_create(&pid[i],NULL,producer,NULL);
}
for(i=0;i<c;i++)
{
pthread_create(&cid[i],NULL,consumer,NULL);
}
for(i=0;i<p;i++)
{
pthread_join(pid[i],NULL);
}
for(i=0;i<c;i++)
{
pthread_join(cid[i],NULL);
}
return 0;
}
Pratik Kataria is currently learning Springboot and Hibernate.
Technologies known and worked on: C/C++, Java, Python, JavaScript, HTML, CSS, WordPress, Angular, Ionic, MongoDB, SQL and Android.
Softwares known and worked on: Adobe Photoshop, Adobe Illustrator and Adobe After Effects.