Python队列与多线程及文件锁,,队列实现生产-多线程
Python队列与多线程及文件锁,,队列实现生产-多线程
队列实现生产-多线程消费
先看代码
# -*- coding: utf-8 -*-import queueimport threadingmu = threading.Lock()class Producer(threading.Thread): def __init__(self, data_queue, thread_name): super(Producer, self).__init__() self.data_queue = data_queue self.thread_name = thread_name def run(self): for i in range(30): self.data_queue.put(i) print "完成生产:{}".format(i)class Customer(threading.Thread): def __init__(self, data_queue, thread_name): super(Customer, self).__init__() self.data_queue = data_queue self.thread_name = thread_name def run(self): while True: if mu.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() break mu.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 in threads: 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() 函数才会生效,退出线程。
Python队列与多线程及文件锁
相关内容
- 《Python从入门到实践》第四章动手试一试,,4-1 比萨 :
- eBPF监控工具bcc系列九bcc Python,,eBPF监控工具bc
- python计算工资个税,, 1 # -*- c
- 练习:python基础+字符串,,1、执行python
- python 实现简单语音聊天机器人,, 1 # -*- c
- Ubuntu下python的BeautifulSoup和rsa安装方法,,最近因为《信
- python反反爬,爬取猫眼评分,,python反反爬,
- 打造最全皮肤,Python采集英雄联盟(LOL)官网数据!,
- python 随机生成汉字,,第一种方法:Unic
- python2.7导入mysqldb,,my噶地~~学习了一
评论关闭