Lock版本:
import threading
import random
import time
gLock = threading.Lock()
ALL_MONEY = 1000
TIME_COUNT = 0
class producer(threading.Thread):
def run(self):
global ALL_MONEY
global TIME_COUNT
while True:
money = random.randint(1000, 5000)
gLock.acquire()
if TIME_COUNT >= 10:
gLock.release()
break
ALL_MONEY += money
print("%s本次生产了%d元,总共还剩余%d元" % (threading.current_thread(), money, ALL_MONEY))
TIME_COUNT += 1
gLock.release()
time.sleep(0.5)
class consumer(threading.Thread):
def run(self):
global ALL_MONEY
global TIME_COUNT
while True:
money = random.randint(1000, 8000)
gLock.acquire()
if money <= ALL_MONEY:
ALL_MONEY -= money
print("%s本次消费了%d元,剩余%d元" % (threading.current_thread(), money, ALL_MONEY))
else:
if TIME_COUNT >= 10:
gLock.release()
break
print("%s本次需要消费%d元,剩余金额不足" % (threading.current_thread(), money))
gLock.release()
time.sleep(0.5)
def main():
for x in range(3):
t = consumer(name="消费者线程%d" % x)
t.start()
for x in range(5):
t = producer(name="生产者线程%d" % x)
t.start()
if __name__ == '__main__':
main()
Condition版本:
import threading
import random
import time
gCondition = threading.Condition()
ALL_MONEY = 1000
TIME_COUNT = 0
class producer(threading.Thread):
def run(self):
global ALL_MONEY, TIME_COUNT
while True:
money = random.randint(1000, 10000)
gCondition.acquire()
if TIME_COUNT >= 10:
gCondition.release()
break
ALL_MONEY += money
print("%s本次生产了%d元,总共还剩余%d元" % (threading.current_thread(), money, ALL_MONEY))
TIME_COUNT += 1
gCondition.notify_all()
gCondition.release()
time.sleep(0.5)
class consumer(threading.Thread):
def run(self):
global ALL_MONEY
global TIME_COUNT
while True:
money = random.randint(1000, 5000)
gCondition.acquire()
“”" 此处需要用while来循环判断钱是否足够,如果用if,钱不足时当前进程暂停,
后面可能还有其他进程,当钱生产够了时,当前进行就排在其他进程后面,
可能等其他进程消耗之后,当前进程需要的钱再次不足,因此需要用while"""
while ALL_MONEY < money:
print("%s本次需要消费%d元,剩余金额不足" % (threading.current_thread(), money))
if TIME_COUNT >= 10:
gCondition.release()
return
gCondition.wait()
ALL_MONEY -= money
print("%s本次消费了%d元,剩余%d元" % (threading.current_thread(), money, ALL_MONEY))
gCondition.release()
time.sleep(0.5)
def main():
for x in range(3):
t = consumer(name=“消费者线程%d” % x)
t.start()
for x in range(5):
t = producer(name="生产者线程%d" % x)
t.start()
if name == ‘main’:
main()