Operating system experiment (1) python producer consumer problem

Producer-consumer problem:

Also known as the Bounded-buffer problem, it is a classic case of multi-thread synchronization problems. This problem describes what happens when two threads sharing a fixed-size buffer-the so-called "producer" and "consumer"-actually run. The main role of the producer is to generate a certain amount of data into the buffer, and then repeat the process. At the same time, consumers are consuming these data in the buffer. The key to this problem is to ensure that producers will not add data when the buffer is full, and consumers will not consume data when the buffer is empty.
Model structure
Insert picture description here

Solutions:

This problem involves two important concepts in operating system process management-synchronization and mutual exclusion.
Synchronization means that producers and consumers need to work together, and consumers are not allowed to pick up products in an empty buffer; and producers are also not allowed to put products into a buffer that is full of products and has not been taken away.
Mutual exclusion means that any two members of the producer and the consumer, the producer and the producer, and the consumer and the consumer must use the buffer zone exclusively. When a member enters the buffer to store/take products, other members will be locked outside the door and wait in line (blocked); when it is over, the leader of the team will be notified to enter.

Fake code:

According to operating system theory, we need three semaphores, named full, empty, and mutex respectively, to represent the number of available resources of the consumer, the number of available resources of the producer, and whether the buffer is available. Initial value: full=0 (the consumer has no resources available), empty=n (the producer has n resources available, n represents the buffer size), mutex=1 (the buffer is available).

semaphore mutex=1, empty=n, full=0;
item buffer[n] ;int in=0,out=0;void producer(){
    
       //生产者进程
      do{
    
    
            producer an item nextp; //产一个产品
            wait(empty); //empty减1
            wait(mutex);//加锁
            buffer[in]=nextp;
            in=(in+1)% n;  //移动生产指针
            signal(mutex);//解锁
            signal(full); //full增1
      }while(TRUE);
}
void consumer(){
    
    //消费者进程
     do{
    
    
            wait(full); 
            wait(mutex);
            nextc=buffer[out];
            out= (out+1)%n;
            signal(mutex);
            signal(empty);
            consumer the item in nextc;
            ...  
      }while(TRUE);
} 

Multi-threaded implementation

The production capacity of the fixed producer and the consumption of the consumer each time are 1 or it can be set to a random value.

Part 1: Consumer
class Consumer(threading.Thread):
    def run(self):
        #全局变量
        global Resources
        global UseTime
        global ProduceTime
        while True:
            # resource2 = random.randint(100,1000)  #随机产生一个消耗资源量
            resource2 = 1
            Lock.acquire()  #开启线程锁
            if resource2 <= Resources:
                Resources -= resource2
                print("{}消费者目前拥有的资源量为{},使用了{}资源量,还剩余{}资源量".format(threading.current_thread(),Resources+resource2, resource2, Resources))
            else:
                if UseTime >= ProduceTime:  #如果消费者拥有的资源小于消耗的资源,则退出
                    Lock.release() #释放线程锁
                    break
                print("{}消费者需要使用{}的资源,目前拥有的资源量为{},所以资源不足".format(threading.current_thread(),Resources,resource2))
            Lock.release()
            time.sleep(0.3)

Part 2: Producer class
class Producer(threading.Thread):
    def run(self):
        #全局变量
        global Resources
        global UseTime
        global ProduceTime
        while True:
            # resource1 = random.randint(100,1000)  #随机产生一个生产的资源量
            resource1 = 1
            Lock.acquire()  #开启线程锁
            if UseTime >= ProduceTime:
                Lock.release() #释放线程锁
                break
            UseTime += 1
            Resources += resource1 #生产者增加资源
            print("%s生产者生产了%d的使用资源,现在总共还有%d的可用资源量"%(threading.current_thread(),resource1,Resources))
            Lock.release()
            time.sleep(0.3)
The third part: the main function part
import time
import random
import threading

Resources = 0 #初始可用资源量
Lock = threading.Lock()  #创建线程锁
ProduceTime = 30 #定义一个生产次数
UseTime = 0 #初始化使用次数
def main():
    for i in range(4):
        t=Consumer(name='消费者%d'%(i))
        t.start()
    for x in range(4):
        y = Producer(name='生产者%d'%(x))
        y.start()
 if __name__ == '__main__':
    main()

operation result
Insert picture description here

Guess you like

Origin blog.csdn.net/qq_41606378/article/details/105829210