A clan of people eat their dinners from a large pan that can hold K servings of food. When a
hungry person wants to eat, s/he helps himself from the pan with one serving, unless it is empty.
if the pan is empty, the person wakes up the cook and then waits until the cook has refilled the pan.
A hungry person thread executes the following unsynchronized code:
while (true) {
getServingFromPan();
eat();
}
Thus as shown above, a hungry person p will invoke this getServingFromPan() as long as he is
hungry and there is food in the pan. In a single invocation of getServingFromPan(), the p will get
one serving.
The single cook thread runs the following unsynchronzied code:
while (true) {
putServingsInPan(K);
}
The synchronization constraints are:
• Persons cannot invoke getServingFromPan if the pan is empty.
• The cook can invoke putServingsInPan only if the pan is empty.
#include <iostream>
using namespace std;
int K=0;
void getServingFromPan(){
K--;
}
void eat(){
cout << "EAT";
}
void putServingsInPan(int J){
K=10;
}
int main()
{
int p=10;
for (int i=0; i<p; ++i){
while (K==0) {
putServingsInPan(K);
}
while (K>0) {
getServingFromPan();
eat();
}
}
return 0;
}
Comments
Leave a comment