软考知识-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)
s1.acquire()
cache = pro
print('生产者:送进去产品',pro,'缓存中产品:',cache)
s2.release()
print('生产者:结束----')
count -= 1
time.sleep(0.5)
def consumer():
global con,s1,s2,cache
count = 5
while count:
print('消费者:等待----',s1,s2)
s2.acquire()
con = cache
cache = '空'
print('消费者:缓存取出产品:',con,'缓存中产品个数:',cache)
s1.release()
print('消费者:消费产品', con)
print('消费者:结束----')
count -= 1
if __name__ == '__main__':
t1 = threading.Thread(target=producer)
t2 = threading.Thread(target=consumer)
t1.start()
t2.start()
|