软考知识-Python实现PV *** 作

软考知识-Python实现PV *** 作,第1张

软考知识-Python实现PV *** 作 软考知识-Python实现PV *** 作

防盗标识:本文源文地址,未授权禁止转载https://blog.csdn.net/weixin_44331765/article/details/122784219

import threading, time
import random

s1 = threading.Semaphore(value=1)
s2 = threading.Semaphore(value=0)
pro = 0
con = 0
cache = 0
product_list = ['小米手机','华为手机','vivo','电脑','手环']

def producer():
    global pro,s1,s2,cache
    count = 4
    for i in range(len(product_list)):
        print('生产者:开始',s1,s2)
        pro = random.choice(product_list)
        print('生产者:生产:',pro)
        # 执行P(s2) *** 作
        s1.acquire()
        cache = pro
        print('生产者:送进去产品',pro,'缓存中产品:',cache)
        # 执行V(s1) *** 作
        s2.release()
        print('生产者:结束----')
        count -= 1
        time.sleep(0.5)

def consumer():
    global con,s1,s2,cache
    count = 5
    while count:
        print('消费者:等待----',s1,s2)
        # 执行P(s2) *** 作
        s2.acquire()
        con = cache
        cache = '空'
        print('消费者:缓存取出产品:',con,'缓存中产品个数:',cache)
        # 执行V(s1) *** 作
        s1.release()
        print('消费者:消费产品', con)
        print('消费者:结束----')
        count -= 1

if __name__ == '__main__':
    t1 = threading.Thread(target=producer)
    t2 = threading.Thread(target=consumer)
    t1.start()
    t2.start()


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5721101.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-18
下一篇 2022-12-18

发表评论

登录后才能评论

评论列表(0条)

保存