操作系统问题三、一个模拟管程(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()
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值