队列实现生产-多线程消费
先看代码
#-*- coding: utf-8 -*-
importqueueimportthreading
mu=threading.Lock()classProducer(threading.Thread):def __init__(self, data_queue, thread_name):
super(Producer, self).__init__()
self.data_queue=data_queue
self.thread_name=thread_namedefrun(self):for i in range(30):
self.data_queue.put(i)print "完成生产:{}".format(i)classCustomer(threading.Thread):def __init__(self, data_queue, thread_name):
super(Customer, self).__init__()
self.data_queue=data_queue
self.thread_name=thread_namedefrun(self):whileTrue:ifmu.acquire(True):try:
data= self.data_queue.get(True, 3)print "%s完成消费: %s" %(self.thread_name, data)
with open(‘ax.txt‘, ‘a+‘) as f:
f.write(‘customer_‘+str(data)+‘\n‘)except:
self.data_queue.task_done()breakmu.release()
q=queue.Queue()
producer= Producer(q, ‘Pro‘)
producer.start()
producer.join()
threads=[]for i in range(1, 5):
name= ‘Cus{}‘.format(i)
customer=Customer(q, name)
customer.start()
threads.append(customer)for j inthreads:
j.join()
Python队列使用的是queue模块,多线程使用的是threading模块
生产者:Producer类,不断的向队列中添加元素,这里是添加数字1-30.
消费者:Customer类,创建4个线程,然后不断的从队列中取出元素进行“消费”。
这里有两个注重点:
1)写操作,因为这里是要写入文件的,所以,如果不加锁的话,就会出现顺序混乱,可能会覆盖数据的情况。
对此,可以先创建一个锁,进行写操作时就加上锁,完成后释放锁
# 创建锁
mu=threading.Lock()
# 加锁
mu.acquire()
# 释放锁
mu.release()
2) 线程退出,当队列为空时,我想要退出线程结束。如果不做点东西(超时设置),线程就会一直想要从队列获取元素而阻塞,不会退出。
所以,从队列获取元素时设置超时时间,超时后会引发异常。上面代码 self.data_queue.get(True, 3) 设置了超时时间为3秒,当队列为空后超过3秒,就会引发异常,执行
self.data_queue.task_done(),task_done()函数会给线程发送信号,后续的 join() 函数才会生效,退出线程。