利用python线程编程实现生产者与消费者关系

    python中,有thread和threading模块支持多线程编程,而threading是thread的封装,所以一般情况下使用threading模块进行编程。

    对于生产者和消费者关系的python实现,代码如下:

import threading

class Producer(threading.Thread):
    def __init__(self, threadname):
        threading.Thread.__init__(self, name = threadname)
    def run(self):
        global x
        con.acquire()
        if x == 1000000:
            con.wait()
            pass
        else:
            for i in range(1000000):
                x = x + 1
            con.notify()
        print x
        con.release()

class Consumer(threading.Thread):
    def __init__(self, threadname):
        threading.Thread.__init__(self, name = threadname)
    def run(self):
        global x
        con.acquire()
        if x == 0:
            con.wait()
            pass
        else:
            for i in range(1000000):
                x = x-1
            con.notify()
        print x
        con.release()
 
con = threading.Condition()
x = 0
p = Producer('Producer')
c = Consumer('Consumer')
p.start()
c.start()
p.join()
c.join()
print x

 

    其中,join()方法用于等待线程完成,acquire和release方法用于线程同步

 

运行结果:


    在python中可以使用Queue对象实现多个生产者和多个消费者的关系模型,下面代码是一个简单的实现:

import threading
import time
import Queue


class producer(threading.Thread):
    def __init__(self, threadname):
        threading.Thread.__init__(self, name = threadname)
    def run(self):
        global queue
        queue.put(self.getName())
        print self.getName(), 'put ', self.getName(), ' to queue'


class consumer(threading.Thread):
    def __init__(self, threadname):
        threading.Thread.__init__(self, name = threadname)
    def run(self):
        global queue
        print self.getName(), 'get ', queue.get(), 'from queue'


queue = Queue.Queue()
prolist = []
conlist = []
for i in range(10):
    p = producer('Producer' + str(i))
    prolist.append(p)
for i in range(10):
    c = consumer('Consumer' + str(i))
    conlist.append(c)
for i in prolist:
    i.start()
    i.join()
for i in conlist:
    i.start()
    i.join()


运行结果:


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值