python 生产者消费者模型

第一种:

from Queue import Queue
import random,threading,time

#生产者类
class Producer(threading.Thread):
    def __init__(self, name,queue):
        threading.Thread.__init__(self, name=name)
        self.data=queue

    def run(self):
        for i in range(5):
            print("%s is producing %d to the queue!" % (self.getName(), i))
            self.data.put(i)
            time.sleep(random.randrange(10)/5)
        print("%s finished!" % self.getName())

#消费者类
class Consumer(threading.Thread):
    def __init__(self,name,queue):
        threading.Thread.__init__(self,name=name)
        self.data=queue
    def run(self):
        for i in range(5):
            val = self.data.get()
            print("%s is consuming. %d in the queue is consumed!" % (self.getName(),val))
            time.sleep(random.randrange(10))
        print("%s finished!" % self.getName())

def main():
    queue = Queue()
    producer = Producer('Producer',queue)
    consumer = Consumer('Consumer',queue)

    producer.start()
    consumer.start()

    producer.join()
    consumer.join()
    print 'All threads finished!'

if __name__ == '__main__':
    main()

第二种

#!/usr/bin/python
# coding: utf-8

from Queue import Queue
import random,threading,time
import thread

class TestMultThreadMode( threading.Thread ):
    def __init__( self, queue ):
        threading.Thread.__init__( self )
        self.data = queue
        
    def producer( self ):
        for i in range( 5 ):
            print 'this is %s%d' % ( "producer", i )
            self.data.put( i )
            time.sleep( random.randrange(10) / 5 )
        print '%s end!' % 'producer'
        
    def consumer( self ):
        for i in range ( 5 ):
            print 'this is %s%d' % ( "consumer", i )
            self.data.get( i )
            time.sleep( random.randrange(10) / 5 )
        print '%s end!' % 'consumer'

def main():
    queue = Queue()
    testThread = TestMultThreadMode( queue )
    thread.start_new_thread( testThread.producer, () )
    thread.start_new_thread( testThread.consumer, () )
    while True:
        pass

if __name__=="__main__":
    main()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值