python 繼承線程的類 不能通過標志位結束線程
問題描述
在測試生產消費者模型的時候遇到這樣一個問題,在繼承線程后 加了個標志位 mark
class Consumer(threading.Thread): def __init__(self, queue):threading.Thread.__init__(self)self._queue = queueself.mark = True def run(self):while self.mark: msg = self._queue.get() if isinstance(msg, str) and msg == ’quit’:break print('I’m a thread, and I received %s!!' % msg)print(’Bye byes!’)
def producer(): q = queue.Queue() worker = Consumer(q) worker.start() # 開啟消費者線程 start_time = time.time() while time.time() - start_time < 5:q.put(’something at %s’ % time.time())time.sleep(1) worker.mark = Flese worker.join()
我原先指望 通過這個標志位來實現線程的結束控制,但實際效果是程序卡死在worker.join()完全沒有退出。
請教下,這是什么原因?
問題解答
回答1:class Consumer(threading.Thread): def __init__(self, queue):threading.Thread.__init__(self)self._queue = queueself.mark = True def run(self):while self.mark: try:msg = self._queue.get(block=False) # 非阻塞print('I’m a thread, and I received %s!!' % msg) except:pass print(’self.mark’,self.mark)print(’Bye byes!’)def producer(): q = queue.Queue() worker = Consumer(q) worker.start() # 開啟消費者線程 start_time = time.time() while time.time() - start_time < 5:q.put(’something at %s’ % time.time())time.sleep(1) worker.mark = False worker.join()
相關文章:
1. Docker for Mac 創建的dnsmasq容器連不上/不工作的問題2. html5 - javascript讀取自定義屬性的值,有的能夠取到,有的取不到怎么回事??3. html - Python2 BeautifulSoup 提取網頁中的表格數據及連接4. python - PyCharm里的一個文件不小心忽略了wx包5. android - VideoView與百度Map沖突6. python - (2006, ’MySQL server has gone away’)7. 小白學python的問題 關于%d和%s的區別8. python - 使用eclipse運行django代碼,修改了views.py這個文件,但是瀏覽器顯示的還是原有沒修改的結果,怎么處理?9. django - pycharm 如何配置 python3 的開發環境?10. win10 Apache24+PHP8.0,Apache不能正常加載php.ini。
