老子不玩了!公開操作系統(tǒng)算法題大全
https://www.geeksforgeeks.org/producer-consumer-problem-using-semaphores-set-1/?ref=lbp
Difficulty Level :?Easy
Last Updated :?20 Sep, 2021
Prerequisite –?Semaphores in operating system,?Inter Process Communication?
Producer consumer problem is a classical synchronization problem. We can solve this problem by using semaphores.?
A?semaphore?S is an integer variable that can be accessed only through two standard operations : wait() and signal().?
The wait() operation reduces the value of semaphore by 1 and the signal() operation increases its value by 1.?
wait(S){ while(S<=0); ? // busy waiting S--; } signal(S){ S++; }
Semaphores are of two types:??
Binary Semaphore –?This is similar to mutex lock but not the same thing. It can have only two values – 0 and 1. Its value is initialized to 1. It is used to implement the solution of critical section problem with multiple processes.?
?Counting Semaphore –?Its value can range over an unrestricted domain. It is used to control access to a resource that has multiple instances.?
?
Problem Statement –?We have a buffer of fixed size. A producer can produce an item and can place in the buffer. A consumer can pick items and can consume them. We need to ensure that when a producer is placing an item in the buffer, then at the same time consumer should not consume any item. In this problem, buffer is the critical section.?
To solve this problem, we need two counting semaphores – Full and Empty. “Full” keeps track of number of items in the buffer at any given time and “Empty” keeps track of number of unoccupied slots.?
Initialization of semaphores –?
mutex = 1?
Full = 0 // Initially, all slots are empty. Thus full slots are 0?
Empty = n // All slots are empty initially?
Solution for Producer –?