python多线程队列文件_Python队列与多线程及文件锁

队列实现生产-多线程消费

先看代码

#-*- 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() 函数才会生效,退出线程。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值