homework5 Version 0 |
|
👤 Author: by 1730854984qqcom 2020-10-30 03:15:26 |
The problem:
With a printer, when I want to calculate a piece of data and print it out, there's a very small chance that I'll get a blank typed copy. When this happens, I have a critical-section problem. In this case, the data computing process and the printing process share the same buffer, and the printing process performs the printing while the data is still being computed.
The tool:
Faced with this problem, we can use a synchronization tool called a semaphore. A semaphore is an integer variable that, in addition to initialization, can only be accessed through two standard atomic operations: wait() and signal().In wait() and signal() operations, changes to the integer value of a semaphore must be performed inseparably, that is, while one process modifies the semaphore, no other process can simultaneously modify the value of the same semaphore.
Problem Solution:
semaphore empty=0;
semaphore full=1;
void Calculate()
{
while(1)
{
wait(empty);
//Calculate;
signal(full);
}
}
void Print()
{
while(1)
{
wait(full);
//print;
signal(empty);
}
}