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()
运行结果: