Python3生產者/消費者模式
import threading
import queue,time,random
class Goods:#產品類
def __init__(self):
self.count = 0
def add(self,num = 1):
self.count += num
def sub(self):
if self.count>=0:
self.count -= 1
def empty(self):
return self.count <= 0
class Producer(threading.Thread):#生產者類
def __init__(self,condition,goods,sleeptime = 1):#sleeptime=1
threading.Thread.__init__(self)
self.cond = condition
self.goods = goods
self.sleeptime = sleeptime
def run(self):
cond = self.cond
goods = self.goods
while True:
cond.acquire()#鎖住資源
goods.add()
print("產品數量:",goods.count,"生產者線程")
cond.notifyAll()#喚醒全部等待的線程--》其實就是喚醒消費者進程
cond.release()#解鎖資源
time.sleep(self.sleeptime)
class Consumer(threading.Thread):#消費者類
def __init__(self,condition,goods,sleeptime = 2):#sleeptime=2
threading.Thread.__init__(self)
self.cond = condition
self.goods = goods
self.sleeptime = sleeptime
def run(self):
cond = self.cond
goods = self.goods
while True:
time.sleep(self.sleeptime)
cond.acquire()#鎖住資源
while goods.empty():#如無產品則讓線程等待
cond.wait()
goods.sub()
print("產品數量:",goods.count,"消費者線程")
cond.release()#解鎖資源
g = Goods()
c = threading.Condition()
pro = Producer(c,g)
pro.start()
con = Consumer(c,g)
con.start()
Python的鎖
import threading
import time
private_lock = threading.RLock()
num = 0
class MyThread(threading.Thread):
def __init__(self, name):
threading.Thread.__init__(self)
self.t_name = name
def run(self):
global num
while True:
private_lock.acquire()
if num > 4:
print("%s" % self.t_name)
time.sleep(5)
private_lock.release()
break
num += 1
private_lock.release()
def test1():
thread1 = MyThread('A')
thread2 = MyThread('B')
thread1.start()
thread2.start()
if __name__ == '__main__':
test1()