1.生产者和消费者模式的lock版:
import threading
import random
import time
gMoney = 1000
gLock = threading.Lock()
gTotalTime = 10
gTime = 0
class Producer(threading.Thread):
def run(self):
global gMoney
global gTime
while True:
money = random.randint(200,1000)
gLock.acquire()
if gTime >= gTotalTime:
gLock.release()
break
gMoney += money
print("%s挣了%d元前,剩余金额:%d" % (threading.current_thread(),money,gMoney))
gTime +=1
print(gTime)
gLock.release()
time.sleep(0.5)
class Consumer(threading.Thread):
def run(self):
global gMoney
while True:
money = random.randint(200, 1000)
gLock.acquire()
if gMoney > money:
gMoney -= money
print("%s消费了%d元钱,剩余金额:%d" % (threading.current_thread(), money, gMoney))
else:
if gTime >= gTotalTime:
gLock.release()
break
print("%s消费了%d元钱,剩余金额:%d,余额不足" % (threading.current_thread(), money, gMoney))
gLock.release()
time.sleep(0.5)
def main():
for x in range(5):
t = Producer(name="生产者线程:%d" % x)
t.start()
for x in range(3):
t = Consumer(name="消费者线程:%d" % x)
t.start()
if __name__ == '__main__':
main()
2.生产者和消费者模式的condition版:
import threading
import random
import time
gMoney = 0
gCondition = threading.Condition()
gTotalTime = 10
gTime = 0
class Producer(threading.Thread):
def run(self):
global gMoney
global gTime
while True:
money = random.randint(200,1000)
gCondition.acquire() #上锁
if gTime >= gTotalTime:
gCondition.release()
break
gMoney += money
print("%s挣了%d元前,剩余金额:%d" % (threading.current_thread(),money,gMoney))
gTime +=1
gCondition.notify_all() #通知阻塞的线程
gCondition.release()
time.sleep(0.5)
class Consumer(threading.Thread):
def run(self):
global gMoney
while True:
money = random.randint(200, 1000)
gCondition.acquire()
gMoney -= money
while gMoney<money:
if gTime>= gTotalTime:
gCondition.release()
return
print("%s花了%d元钱,剩余金额:%d,余额不足" % (threading.current_thread(), money, gMoney))
gCondition.wait()
print("%s花了%d元钱,剩余金额:%d" % (threading.current_thread(), money, gMoney))
gCondition.release()
time.sleep(0.5)
def main():
for x in range(3):
t = Producer(name="生产者线程:%d" % x)
t.start()
for x in range(3):
t = Consumer(name="消费者线程:%d" % x)
t.start()
if __name__ == '__main__':
main()
万水千山总是情,点个关注行不行。