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 dataif data == 5: raise ValueError(’over’) except ValueError as e:#通知生產者結束#如何實現?
問題解答
回答1:我的方法:添加一個 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 = 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 我也結束了'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:# 通知生產者結束# 如何實現?print 'consumer 我結束了', 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的存在,其實多線程有的時候并不是最好的選擇,具體什么時候使用,網上也說的很多了,樓主也可以結合自己的業務情況舍取多線程模塊。
回答2:簡單的話,就直接把錯誤raise出來,然后讓進程自己崩潰掉就好了.或者,你也可以用異常處理把消費者的run包裹起來,捕獲這個異常,然后再控制生產者的線程就好了.
相關文章:
1. javascript - immutable配合react提升性能?2. javascript - sublime快鍵鍵問題3. phpstudy8.1支持win11系統嗎?4. 配置Apache時,添加對PHP的支持時語法錯誤5. vue.js - Vue 如何像Angular.js watch 一樣監聽數據變化6. css - 寫頁面遇到個布局問題,求大佬們幫解答,在線等,急!~7. 實現bing搜索工具urlAPI提交8. javascript - nodejs關于進程間發送句柄的一點疑問9. Apache 已經把網站根目錄的改為allow from all了,但是服務器還是不能訪問?10. javascript - 移動端上不能實現拖拽布局嗎?

網公網安備