#include <iostream> #include <stdlib.h> #include <fstream> #include <time.h> #include <conio.h> #define N 100 using namespace std; int arr[N]; int arrLength = 0,counter = 0; class doTrade { public: doTrade() { myFile.open("text.txt"); conState = true; proState = true; } void consumer(); void producer(); private: ofstream myFile; bool conState,proState; }; void doTrade::producer() { // Producer goes to sleep if(arrLength == N-1) { if(proState == true) myFile << "producer goes to sleep [P S]" << endl; proState = false; } else { if(proState == true){ myFile << "producer produces [P]" << endl; arr[arrLength] = 1; arrLength ++ ; counter++; } else myFile << "producer can't produce because it is asleep [P C]" << endl; } //waking up consumer if(arrLength == 1) { if(conState == false){ myFile << "producer wakes up [P W]" << endl; conState = true; } } } void doTrade::consumer() { //consumer goes to sleep if(arrLength == 0) { if(conState == true){ myFile << "COnsumer goes to sleep [C S]"<<endl; conState = false; } } else { if(conState == true){ myFile << "Consumer consumes [C ]" << endl; arr[arrLength] = 2; arrLength--; counter--; } else myFile << "consumer can't consume beacuse it is asleep. [C C]" << endl; } //consumer cant wake up producer so once producer is asleep both will sleep forever } int main() { srand(time(NULL)); doTrade p1; double i = 0; int a; while(i <= 15000) { a = rand()%2; if(a) p1.consumer(); else p1.producer(); i++; } return 0; }
C and C++ programs, games, softwares. Easy programming guide. Learn to code and enjoy coding in CoderNepal
Home » Process Management » C++ code for solving Producer-Consumer problem using sleep and wake up calls
Tuesday, April 11, 2017
C++ code for solving Producer-Consumer problem using sleep and wake up calls
This is the solution for Producer-Consumer problem using sleep and wake up calls
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment