11.python并发入门(part8 基于线程队列实现生产者消费者模型)

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了11.python并发入门(part8 基于线程队列实现生产者消费者模型)相关的知识,希望对你有一定的参考价值。

一、什么是生产者消费者模型?

生产者就是生产数据的线程,消费者指的就是消费数据的线程。

在多线程开发过程中,生产者的速度比消费者的速度快,那么生产者就必须等待消费者把数据处理完,生产者才会产生新的数据,相对的,如果消费者处理数据的速度大于生产者,那么消费者就必须等待生产者。

为了解决这种问题,就有了生产者消费者模型。


生产者与消费者模型,是通过一个容器,来解决生产者和消费者之间的耦合性问题,生产者和消费者之间并不会直接通信,这样生产者就无需等待消费者处理完数据,生产者可以直接把数据扔给队列,这个时候消费者也无需找生产者要数据,直接去队列中取数据,这个队列,起到的就是一个缓冲区的作用,具有平衡生产者和消费者的处理能力。


二、基于队列的生产者消费者模型的示例。

ver1:

#!/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

        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()


本文出自 “reBiRTH” 博客,请务必保留此出处http://suhaozhi.blog.51cto.com/7272298/1925548

以上是关于11.python并发入门(part8 基于线程队列实现生产者消费者模型)的主要内容,如果未能解决你的问题,请参考以下文章

11.python并发入门(part3 多线程与互斥锁)

11.python并发入门(part5 event对象)

11.python并发入门(part1 初识进程与线程,并发,并行,同步,异步)

11.python并发入门(part12 初识协程)

11.python并发入门(part9 多线程模块multiprocessing基本用法)

11.python并发入门(part2 threading模块的基本使用)