python中生產(chǎn)者消費者線程問題
問題描述
在使用python的多線程時,使用了生產(chǎn)者消費者模式,一般都是消費者接受生產(chǎn)者的數(shù)據(jù)執(zhí)行某些操作,但是現(xiàn)在這個消費者線程遇到了異常,需要終止執(zhí)行,但是生產(chǎn)者線程因為還在生產(chǎn)數(shù)據(jù),主線程在等待它執(zhí)行完。目前想當消費者線程遇到錯誤時能夠通知生產(chǎn)者線程,我掛了,你也結(jié)束吧。請問大家有什么好的實現(xiàn)方法
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 dataif data == 5: raise ValueError(’over’) except ValueError as e:#通知生產(chǎn)者結(jié)束#如何實現(xiàn)?
問題解答
回答1:我的方法:添加一個 flag 標識。
先看結(jié)果吧:
更多廢話也不多說了,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 = queueself.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 我也結(jié)束了'break time.sleep(2)class Consumer(threading.Thread): def __init__(self, queue, flag):super(Consumer, self).__init__()self.queue = queueself.flag = flag def run(self):while True: try:length = len(self.queue)print 'consumer queue', self.queueif length > 5: self.flag.pop() # 注意我是flag raise ValueError(’over’)self.queue.pop(0) except ValueError as e:# 通知生產(chǎn)者結(jié)束# 如何實現(xiàn)?print 'consumer 我結(jié)束了', ebreak# raise(e) time.sleep(4)queue = [1, 2, 3]flag = [0] # 表示正常Consumer(queue, flag).start()time.sleep(1)Producer(queue, flag).start()
最后說說python的多線程,由于GIL的存在,其實多線程有的時候并不是最好的選擇,具體什么時候使用,網(wǎng)上也說的很多了,樓主也可以結(jié)合自己的業(yè)務(wù)情況舍取多線程模塊。
回答2:簡單的話,就直接把錯誤raise出來,然后讓進程自己崩潰掉就好了.或者,你也可以用異常處理把消費者的run包裹起來,捕獲這個異常,然后再控制生產(chǎn)者的線程就好了.
相關(guān)文章:
1. mysql - 記得以前在哪里看過一個估算時間的網(wǎng)站2. MySQL中的enum類型有什么優(yōu)點?3. python - 有什么好的可以收集貨幣基金的資源?4. javascript - 關(guān)于<a>元素與<input>元素的JS事件運行問題5. python - 啟動Eric6時報錯:’qscintilla_zh_CN’ could not be loaded6. php - 微信開發(fā)驗證服務(wù)器有效性7. ID主鍵不是自增的嗎 為什么還要加null8. mysql - 查詢字段做了索引為什么不起效,還有查詢一個月的時候數(shù)據(jù)都是全部出來的,如果分拆3次的話就沒問題,為什么呢。9. css - 新手做響應(yīng)式布局, 斷點過后右側(cè)出現(xiàn)空白,求幫助,謝謝。10. javascript - vue 怎么渲染自定義組件
