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. docker - 各位電腦上有多少個容器啊?容器一多,自己都搞混了,咋辦呢?2. android studio總是在processes running好久3. java - 請問在main方法中寫成對象名.屬性()并賦值,與直接參參數賦值輸錯誤是什么原因?4. MySQL數據庫中文亂碼的原因5. 關docker hub上有些鏡像的tag被標記““This image has vulnerabilities””6. macos - mac下docker如何設置代理7. docker不顯示端口映射呢?8. css - C#與java開發Windows程序哪個好?9. docker gitlab 如何git clone?10. docker-compose 為何找不到配置文件?
