第五章 爬虫进阶(五) 2020-01-22


五、 Lock版生产者和消费者模式(2


续上例

示例代码:


import threading

import random

import time

 

gMoney= 0

gLock= threading.Lock()

gTimes= 0

 

 

class Producer(threading.Thread):

    def run(self):

        global gMoney

        global gTimes

        while True:

            gLock.acquire()

            if gTimes >= 10:

                gLock.release()

                break

            money = random.randint(0, 100)

            gMoney += money

            gTimes += 1

            print("%s生产了%d元钱" %(threading.current_thread().name, money))

            time.sleep(2)

            gLock.release()

 

 

class Consumer(threading.Thread):

    def run(self) -> None:

        global gMoney

        while True:

            gLock.acquire()

            money = random.randint(0, 100)

            if gMoney >= money:

                gMoney -= money

                print("%s消费了%d元钱" %(threading.current_thread().name, money))

                time.sleep(2)

            else:

                if gTimes >= 10:

                    gLock.release()

                    break

                print("%s消费者想消费%d元钱,但是余额只有%d"% (threading.current_thread().name, money, gMoney))

            gLock.release()

 

 

def main():

    for x in range(5):

        th = Producer(name="生产者%d号" % x)

        th.start()

 

    for x in range(5):

        th = Consumer(name="消费者%d号" % x)

        th.start()

 

 

if __name__== '__main__':

    main()



上一篇文章 第五章 爬虫进阶(四) 2020-01-21 地址:

https://www.jianshu.com/p/f0ccbc3a538c

下一篇文章 第五章 爬虫进阶(六) 2020-01-23 地址:

https://www.jianshu.com/p/3096657cebfc



以上资料内容来源网络,仅供学习交流,侵删请私信我,谢谢。

你可能感兴趣的:(第五章 爬虫进阶(五) 2020-01-22)