【爬虫】Load版的生产者和消费者模式

'''
Lock版的生产者和消费者模式
'''

import threading
import random
import time

gMoney = 1000       # 原始金额
gLoad = threading.Lock()
gTime = 0           # 生产次数

class Producer(threading.Thread):
    def run(self):
        global gMoney
        global gTime
        while True:
            gLoad.acquire()
            if gTime < 20:
                gTime += 1
                money = random.randint(50,500)
                gMoney += money
                print("生产线程%s生成了%d元,剩余%d元"%(threading.current_thread(),money,gMoney))
            else:
                gLoad.release()
                break
            gLoad.release()
            time.sleep(1)


class Consumer(threading.Thread):
    def run(self):
        global gMoney
        while True:
            gLoad.acquire()
            money = random.randint(50,500)
            if money > gMoney:
                print("%s线程结束,需要消费%d,本金为%d"%(threading.current_thread(), money, gMoney))
                gLoad.release()
                break
            else:
                gMoney -= money
                print("消费线程%s消费了%d元,剩余%d元" % (threading.current_thread(), money, gMoney))
            gLoad.release()
            time.sleep(1)


def main():
    for x in range(5):
        t = Producer(name="生产者线程%s"%x)
        t.start()

    for x in range(3):
        t = Consumer(name="消费者线程%s"%x)
        t.start()


if __name__ == '__main__':
    main()

 

posted @ 2019-02-20 20:06  st--st  阅读(120)  评论(0编辑  收藏  举报