lock锁,但是有个问题是,每个线程运行时,每次都得重新上锁和解锁,会比较耗费cpu资源。
import threading
import time
import random
gMoney = 1000
gTimesT = 10
gTimes = 0
gLock = threading.Lock()
class Producer(threading.Thread):
def run(self):
global gMoney
global gTimesT
global gTimes
while True:
money = random.randint(100,1000)
gLock.acquire()
if gTimes >= gTimesT:
gLock.release()
break
gMoney += money
print('%s生产了%d元钱,剩余%d元钱'%(threading.current_thread(),money,gMoney))
gTimes +=1
gLock.release()
time.sleep(0.5)
class Consumer(threading.Thread):
def run(self):
global gMoney
global gTimesT
global gTimes
while True:
money = random.randint(100,1000)
gLock.acquire()
if gMoney >= money:
gMoney -= money
print('%s消费了%d元钱,剩余%d元钱'%(threading.current_thread(),money,gMoney))
else:
if gTimes >= gTimesT:
gLock.release()
break
print('%s消费者消费%d元钱,剩余%d元钱,不足!')
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()