标签:并且 生产 调用 不一致 reading coding 理解 pass pen
1 import threading 2 # 声明互斥锁 3 lock=threading.Rlock(); 4 def handle(sid):# 功能实现代码 5 lock.acquire() #加锁 6 # writer codeing 7 lock.relase() #释放锁
1 # 声明信号量: 2 sema=threading.Semaphore(0); #无上限检查 3 sema=threading.BuderedSeamphore(1) #有上限检查设置 4 5 apple=1 6 def consumner(): 7 seam.acquire(); # ‐1 8 9 if apple==1: 10 pass 11 else: sema2.release();#+ 1 12 def product(): 13 seam.relarse(); # +1 14 if apple==1: 15 pass 16 else: 17 print("消费:",apple); 18
# -*- coding: utf-8 -*- """ Created on Mon Sep 9 21:49:30 2019 @author: DGW-PC """ # 信号量解决生产者消费者问题 import random; import threading; import time; # 声明信号量 sema=threading.Semaphore(0);# 必须写参数 0 表示可以使用数 sema2=threading.BoundedSemaphore(1); apple=1; def product():#生产者 global apple; apple=random.randint(1,100); time.sleep(3); print("生成苹果:",apple); #sema2.release(); # +1 if apple==1: pass else: sema2.release();#+ 1 def consumer(): print("等待"); sema2.acquire();# -1 if apple==1: pass else: print("消费:",apple); threads=[]; for i in range(1,3): t1=threading.Thread(target=consumer); t2=threading.Thread(target=product); t1.start(); t2.start(); threads.append(t1); threads.append(t2); for x in threads: x.join();
标签:并且 生产 调用 不一致 reading coding 理解 pass pen
原文地址:https://www.cnblogs.com/dgwblog/p/11494915.html