Home > OS >  About the operating system and garden semaphore to solve the problem of producer-consumer in doubt
About the operating system and garden semaphore to solve the problem of producer-consumer in doubt

Time:09-22

//using binary semaphore solve the problem of infinite buffer producer-consumer int count=0;//count as data in a buffer number BinSem s=1, delay=0;//s for binary semaphore, control of producers and consumers into the critical region;//delay for binary semaphore, processing buffer is empty; Void producer () {the while (1) {produce (); SemWaitB (s); Append (); count++; If (count==1) semSignalB (delay);//the buffer is not empty, wake up the consumer process semSignalB (s); }} void consumer () {semWaitB (delay); While (1) {semWaitB (s); Take (); count--; M=count; SemSignalB (s); Consume (); Use m//because at this point in the critical zone, the count could have been one of the following statements before update, lead to delay does not match the if (m==0) semWaitB (delay);//buffer is empty, blocking the consumer process}} 
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --

Routine as above, but if at the time of initial directly in the process of consumption of the count value is not directly into 1 consumption errors in advance?

CodePudding user response:

//using binary semaphore solve the problem of infinite buffer producer-consumer int count=0; 
//count as data in a buffer number BinSem s=1, delay=0;
//s for binary semaphore, control of producers and consumers into the critical region;
//delay for binary semaphore, processing buffer is empty;
Void producer ()
{
While (1)
{produce ();
SemWaitB (s);
Append ();
count++;
If (count==1) semSignalB (delay);//the buffer is not empty, wake up the consumer process
SemSignalB (s);
}
}
Void consumer ()
{
SemWaitB (delay);
While (1) {
SemWaitB (s);
Take ();
count--;
M=count;
SemSignalB (s);
Consume (); Using m//because at this point in the critical zone, the count could have been one of the following statements before update, lead to delay does not match the
If (m==0) semWaitB (delay);//buffer is empty, blocking the consumer process
}
}

The code above
  • Related