python里面生产者和消费者关于线程疑问,python生产者,在使用python的多线
python里面生产者和消费者关于线程疑问,python生产者,在使用python的多线
在使用python的多线程时,使用了生产者消费者模式,一般都是消费者接受生产者的数据执行某些操作,但是现在这个消费者线程遇到了异常,需要终止执行,但是生产者线程因为还在生产数据,主线程在等待它执行完。目前想当消费者线程遇到错误时能够通知生产者线程,我挂了,你也结束吧。请问大家有什么好的实现方法
import threadingclass Producer(threading.Thread): def __init__(self, queue): super(Producer, self).__init__() self.queue = queue def run(self): while True: for i in range(10): self.queue.put(i)class Consumer(threading.Thread): def __init__(self, queue): super(Consumer, self).__init__() self.queue = queue def run(self): while True: try: data = self.queue.get() print data if data == 5: raise ValueError('over') except ValueError as e: #通知生产者结束 #如何实现?
我的方法:
添加一个 flag 标识。
先看结果吧:
更多废话也不多说了,show u the code
#!/usr/bin/python# coding=utf-8import threadingimport timeclass Producer(threading.Thread): def __init__(self, queue, flag): super(Producer, self).__init__() self.queue = queue self.flag = flag def run(self): while True: length = max(self.queue) + 1 print "============================= producer queue", self.queue self.queue.append(length) print 'flag length=', len(self.flag) if len(self.flag) == 0: print "producer 我也结束了" break time.sleep(2)class Consumer(threading.Thread): def __init__(self, queue, flag): super(Consumer, self).__init__() self.queue = queue self.flag = flag def run(self): while True: try: length = len(self.queue) print "consumer queue", self.queue if length > 5: self.flag.pop() # 注意我是flag raise ValueError('over') self.queue.pop(0) except ValueError as e: # 通知生产者结束 # 如何实现? print "consumer 我结束了", e break # raise(e) time.sleep(4)queue = [1, 2, 3]flag = [0] # 表示正常Consumer(queue, flag).start()time.sleep(1)Producer(queue, flag).start()
最后说说python的多线程,由于GIL的存在,其实多线程有的时候并不是最好的选择,具体什么时候使用,网上也说的很多了,楼主也可以结合自己的业务情况舍取多线程模块。
简单的话,就直接把错误raise出来,然后让进程自己崩溃掉就好了.
或者,你也可以用异常处理把消费者的run包裹起来,捕获这个异常,然后再控制生产者的线程就好了.
编橙之家文章,
相关内容
- 在Python中实现js的escape?,pythonescape,js:>>>escape
- Python Flask源码异常处理的问题,pythonflask,Flask versio
- 将mngodb返回对象类型变成字典类型怎么操作,mngodb字典
- 求微博站内应用Django'POST /friendscare/ HTTP/1.1'错误解决方
- Python re正则表达式匹配含有\字符串不成功,python正则表
- bottle服务中创建定时器执行任务 重复执行的问题,bo
- python模块import问题求解,python模块import,我用的是pytho
- Python threadpool模块多线程写文件有必要加锁吗,pythont
- python模块导入from .import中间的点是何意思,python.impor
- Django1.7使用内置comment遇到问题,django1.7comment,Django:1.
评论关闭