1、用函数来实现生产者消费者模型

(1)、源代码如下:

#!/usr/bin/python
#_*_coding:utf-8_*_

import threading
import time
import Queue

import random

def Producer(name, que):
    while True:
        if que.qsize() < 3:
            que.put('baozi')
            print '%s : Made a baozi===================================================' % (name)
        else:
            print '还有3个包子'
        time.sleep(random.randrange(3))

def Consumer(name, que):
    while True:
        try:
            que.get_nowait()
            print '%s Got a baozi' % name
        except Exception:
            print '没有包子'
        time.sleep(random.randrange(3))


q = Queue.Queue()
p1 = threading.Thread(target=Producer, args=['chef1', q])
p2 = threading.Thread(target=Producer, args=['chef2', q])

p1.start()
p2.start()

c1 = threading.Thread(target=Consumer, args=['zhangsan', q])
c2 = threading.Thread(target=Consumer, args=['lisi', q])

c1.start()
c2.start()

(2)、运行结果:

这就形成了抢占资源的结果;


2、用类来实现生产者消费者模型

(1)、源代码如下:

#!/usr/bin/python
#_*_coding:utf-8_*_

from threading import Thread
from Queue import Queue
import time

class Producer(Thread):
    def __init__(self, name, queue):
        self.__Name = name
        self.__Queue = queue
        super(Producer, self).__init__()

    def run(self):
        while True:
            if self.__Queue.full():
                time.sleep(1)
            else:
                self.__Queue.put('baozi')
                time.sleep(1)
                print '%s 生产了一个包子' % (self.__Name)

class Consumer(Thread):
    def __init__(self, name, queue):
        self.__Name = name
        self.__Queue = queue
        super(Consumer, self).__init__()
        
    def run(self):
        while True:
            if self.__Queue.empty():
                time.sleep(1)
            else:
                time.sleep(1)
                self.__Queue.get()
                print '%s 消费了一个包子' % (self.__Name)


que = Queue(maxsize = 100) #队列空间大小,队列是安全的

c1 = Producer('老张', que)
c1.start()

c2 = Producer('老李', que)
c2.start()

c3 = Producer('老马', que)
c3.start()

for item in range(20):
    name = 'chentao%d' % (item,)
    temp = Consumer(name, que)
    temp.start()

(2)、运行结果:


此时也形成了资源的竞争,达到了消费者生产者的模型;