11.python併發入門(part8 基於線程隊列實現生產者消費者模型)

1、什麼是生產者消費者模型?
python

生產者就是生產數據的線程,消費者指的就是消費數據的線程。多線程

在多線程開發過程當中,生產者的速度比消費者的速度快,那麼生產者就必須等待消費者把數據處理完,生產者纔會產生新的數據,相對的,若是消費者處理數據的速度大於生產者,那麼消費者就必須等待生產者。dom

爲了解決這種問題,就有了生產者消費者模型。python2.7


生產者與消費者模型,是經過一個容器,來解決生產者和消費者之間的耦合性問題,生產者和消費者之間並不會直接通訊,這樣生產者就無需等待消費者處理完數據,生產者能夠直接把數據扔給隊列,這個時候消費者也無需找生產者要數據,直接去隊列中取數據,這個隊列,起到的就是一個緩衝區的做用,具備平衡生產者和消費者的處理能力。ide


2、基於隊列的生產者消費者模型的示例。線程

ver1:隊列

#!/usr/local/bin/python2.7utf-8

# -*- coding:utf-8 -*-開發

import timeget

import random

import Queue

import threading

q1 = Queue.Queue()

def producer(name):

    count = 0

    while count < 10:

        print  "making..."

        time.sleep(random.randrange(3))

        q1.put(count)

        print "procucer %s has produced %s baozi...." %(name,count)

        count += 1

        print "ok!"

def consumer(name):

    count = 0

    while count < 10:

        time.sleep(random.randrange(4))

        if not q1.empty():

            data = q1.get()

            print data

            print '\033[32;1mConsumer %s has eat %s baozi...\033[0m' %(name, data)

        else:

            print "not fond baozi"

        count += 1

if __name__ == '__main__':

    p1 = threading.Thread(target=producer,args=('A',))

    c1 = threading.Thread(target=consumer,args=('B',))

    p1.start()

    c1.start()


ver2:

#!/usr/local/bin/python2.7

# -*- coding:utf-8 -*-

import time

import random

import Queue

import threading

q1 = Queue.Queue()

def producer(name):

    count = 0

    while count < 10:

        print  "making..."

        time.sleep(random.randrange(3))

        q1.put(count)

        print "procucer %s has produced %s baozi...." %(name,count)

        count += 1

        q1.task_done()  #給隊列發個信號,告訴隊列put完畢

        #q1.join()

        print "ok!"

def consumer(name):

    count = 0

    while count < 10:

        q1.join() ##監聽生產者發送給隊列的信號

        time.sleep(random.randrange(4))

       # if not q1.empty():

        data = q1.get()

        #q1.task_done()

        print data

        print '\033[32;1mConsumer %s has eat %s baozi...\033[0m' %(name, data)

        #else:

        #print "not fond baozi"

        count += 1

if __name__ == '__main__':

    p1 = threading.Thread(target=producer,args=('A',))

    c1 = threading.Thread(target=consumer,args=('B',))

    c2 = threading.Thread(target=consumer,args=('C',))

    c3 = threading.Thread(target=consumer,args=('D',))

    p1.start()

    c1.start()

    c2.start()

    c3.start()

相關文章
相關標籤/搜索