操作系统问题三、一个模拟管程(Python,之前很少有人做,不是因为难,是因为确实没卵用)

题目 3 :
请用你熟悉的线程库编程实现管程,解决生产者和消费者问题并测试

答案在这:

import threading
import time

class Monitor(object):
    def __init__(self, size):
        self.MaxSize = size
        self.M_buffer = [None] * size
        self.In_P = 0
        self.OUT_P = 0
        self.counts = 0
        self.NotFull = threading.Condition()
        self.NotEmpty = threading.Condition()

    def Append(self, id):
        if self.counts == self.MaxSize:
            self.NotFull.acquire()
            self.NotFull.wait()
            self.NotFull.release()
        else:
            self.M_buffer[self.In_P] = id
            print(self.M_buffer)
            self.In_P = (self.In_P + 1) % self.MaxSize
            self.counts += 1
            self.NotEmpty.acquire()
            self.NotEmpty.notify()
            self.NotEmpty.release()

    def Take(self):
        if self.counts == 0:
            self.NotEmpty.acquire()
            self.NotEmpty.wait()
            self.NotEmpty.release()
        else:
            id = self.M_buffer[self.OUT_P]
            print(self.M_buffer)
            self.OUT_P = (self.OUT_P+1) % self.MaxSize
            self.counts -= 1
            self.NotFull.acquire()
            self.NotFull.notify()
            self.NotFull.release()
            return id

class BasicThread(threading.Thread):
    def __init__(self, func, args):
        '''
        :param func: 调用的对象
        :param args: 调用对象的参数
        '''
        threading.Thread.__init__(self)
        self.func = func
        self.args = args
        self.result = None

    def run(self):
        self.func(*self.args)

def Producer(monitor):
    P_id = 0
    while(True):
        print("生产了:ID-"+str(P_id))
        monitor.Append(id="ID-"+str(P_id))
        P_id += 1

def Customer(monitor):
    while(True):
        time.sleep(2)
        C_id = monitor.Take()
        print("消费了:"+str(C_id))

if __name__ == "__main__":
    Main_Monitor = Monitor(size=30)
    P_Thread = BasicThread(func=Producer, args=(Main_Monitor,))
    C_Thread = BasicThread(func=Customer, args=(Main_Monitor,))
    P_Thread.start()
    C_Thread.start()
    P_Thread.join()
    P_Thread.join()

你可能感兴趣的:(python,thread,object,多线程)