ALL > Computer and Education > courses > university courses > undergraduate courses > Operating System > zstu-(2021-2022)-1 > student homework directories > >
2019329621249陈雅冰homework6 Version 0
👤 Author: by 1422679707qqcom 2021-12-25 17:30:35
Assuming that there are n buffers in the common buffer pool between producers and consumers, producers can produce a product to the buffer and consumers can consume a product from the buffer. Note: producers can't produce at the same time, consumers can't consume at the same time, and they can't produce and consume at the same time. When the buffer is empty, they can't consume, and when the buffer is full, they can't produce. The solution is as follows:
semaphore mutex = 1; //Realize production and consumption, production and production, consumption and consumption
semaphore full = 0, empty = n; //full indicates the number of used buffers, and empty indicates the number of empty buffers.
void producer() {
while(1) {
P(empty); //Each production will reduce an empty buffer. If there is no empty buffer, it will be blocked.
P(mutex); //Guaranteed mutual exclusion
Produce a product;
V(mutex); //Guaranteed mutual exclusion
V(full); //Add one used buffer for each production.
}
}
void consumer() {
while(1) {
P(full); //Each consumption will reduce one used buffer, and block if there is no used buffer.
P(mutex);
Consume a product;
V(mutex);
V(empty); //Add an empty buffer for each production.
}
}

Please login to reply. Login

Reversion History

Loading...
No reversions found.