Description of the problem
Suppose a system has three smoker processes and a supplier process. Each smoker keeps cigarette and smokes it, but to roll up and smoke a cigarette, the smoker needs three kinds of material: tobacco, paper and glue. Of the three smokers, the first one has tobacco, the second owns the paper, and the third has the glue. The supplier process provides an unlimited supply of three materials, each time the supplier puts two materials on the table, a smoker with the leftover material rolls a cigarette and smokes it, and gives the supplier a signal that the supplier will put two other materials on the table, a process that repeats (letting three smokers take turns to smoke).
Problem analysis
1) Relationship analysis. The supplier is in sync with three smokers respectively. Since the supplier cannot satisfy two or more smokers at the same time, three smokers are mutually exclusive to the act of smoking (or by taking turns smoking by three smokers to learn
2) Arrange ideas. Obviously there are four processes here. The supplier provided the material to three smokers as a producer.
3) Semaphore setting. The semaphore Offer1, Offer2, and Offer3 respectively represent the resources of the tobacco and paper combination, the resources of the combination of tobacco and glue, and the combination of paper and glue. The semaphore finish is used for mutually exclusive smoking actions.
The code is as follows:
int random; Store random number semaphore offer1=0; Define the amount of signal corresponding to the tobacco and paper combination of resources Semaphore offer2=0; Define the amount of signal corresponding to the combination of tobacco and glue resources Semaphore offer3=0; Define the resource semaphore finish=0 of the corresponding paper and glue combination of the signal volume; Define the semaphore to indicate whether the smoke is complete//provider while (1) {Random = arbitrary integer number; random=random% 3; if (random==0) V (offerl);//provide tobacco and paper else if (random==l) V (offer2); Supply of tobacco and glue else V (OFFER3) //provide paper and glue// any two materials on the table; P (finish);} With the tobacco person while (1) { P (offer3); Take paper and glue, roll into smoke, draw out; V (finish);} Holders of paper while (1) { P (offer2); Tobacco and glue, rolled into smoke, pumped out; V (finish);} Possessing glue while (1) { P (offer1); Take tobacco and paper, roll into smoke, smoke out; V (finish);}
[Classic thread sync problem] Smokers