2019327100017朱奕名homework6 Version 0 |
|
👤 Author: by 1114774057qqcom 2021-12-30 04:49:15 |
A group of producers produce products and provide them to consumers for consumption. In order to enable the producer process and the consumer process to proceed concurrently, a buffer pool with n buffers is set between them, and the producer process puts the products into a buffer; Consumers can take products from a buffer to consume. Although all producer processes and consumer processes run in different ways, they must remain synchronized: consumers are not allowed to take products when a buffer is empty, and producers are not allowed to store products when a buffer is full.
int in = 0 , out = 0 ;
item buffer[n];
semaphore mutex = 1 ;
semaphore empty = n ;
semaphore full = 0 ;
//producer
void producer {
do {
item = produce_item();
wait(empty);
wait(mutex);
buffer[in] = insert_item(item);
in = ( in +1 ) % n ;
signal(mutex);
signal(full);
} while(1)
}
//consumer
void consumer{
do {
wait(full);
wait(mutex);
remove_item(item) = buffer[out] ;
out = ( in +1 ) % n ;
signal(mutex);
signal(empty);
consumer_item(item);
} while(1)
}
void main() {
cobegin
producer();consumer();
coend
}