爬虫19-线程生产者和消费者以及队列

import threading
import random
import time

gMoney = 1000
gLock = threading.Lock()
gTotalTimes = 10
gTimes = 0


class Producer(threading.Thread):
    def run(self):
        global gMoney
        global gTimes
        while True:
            money = random.randint(100,1000)
            gLock.acquire()
            if gTimes >= gTotalTimes:
                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
        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 >= gTotalTimes:
                    gLock.release()
                    break
                print('%s消费者准备消费%d元钱,剩余%d元钱,不足!'%(threading.current_thread(),money,gMoney))
            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()

  

 

from queue import Queue
import threading
import time
def test():

    q = Queue(4)
    for i in range(4):
        q.put(i)

    for i in range(4):
        print(q.get())
    print(q.full())
    print(q.empty())
    print(q.qsize())

def set_value(q):
    index=0
    while True:
        q.put(index)
        index+=1
        time.sleep(1)

def get_value(q):
    while True:
        print(q.get())

def main():
    q=Queue(4)
    t1=threading.Thread(target=set_value,args=[q])
    t2=threading.Thread(target=get_value,args=[q])

    t1.start()
    t2.start()

if __name__ == '__main__':
    main()

  

posted @ 2020-03-15 21:03  胡辣汤王子  阅读(142)  评论(0编辑  收藏  举报