[英]Setting a Variable inside a Running Thread to Stop the Thread
我有一個對象cooker
其run()
方法啟動一個新的線程cookingThread
。 5秒鍾后,我怎么能阻止cookingThread
通過設置變量stopThread
?
嘗試使用cooker.toggle()
首先啟動線程,但是下一個cooker.toggle()
無法停止線程。
下面的代碼給我錯誤NameError: global name 'cookingThread' is not defined
import threading
import time
class Cooker(object):
def __init__(self, recipe):
self.active = False
self.recipe = recipe
def toggle(self):
if not self.active:
self.active = True
self.run()
else:
self.active = False
# How can this stop flag be passed into the running thread?
cookingThread.stopThread = True
def run(self):
cookingThread = CookingThread(self.recipe)
cookingThread.start()
CookingThread
class CookingThread(threading.Thread):
def __init__(self, recipe):
super(CookingThread, self).__init__()
self.recipe = recipe
self.stopThread = False
def run(self):
for i in range(self.recipe):
# Check if we should stop the thread
if self.stopThread:
return
else:
print 'Cooking...'
time.sleep(1)
主要
cooker = Cooker(10)
cooker.toggle() # Starts the thread
time.sleep(5)
cooker.toggle() # Stops the thread (does not work)
問題是cookingThread
是僅在Cooker.run()
方法內部作用域的方法。 該錯誤表明您需要將其聲明為全局方法,以便能夠從所有方法進行訪問。 但這不是一個好習慣。
您可以執行以下操作
import threading
import time
class Cooker(object):
def __init__(self, recipe):
self.active = False
self.recipe = recipe
def toggle(self):
if not self.active:
self.active = True
self.run()
else:
self.active = False
# How can this stop flag be passed into the running thread?
self.cookingThread.stop()
def run(self):
self.cookingThread = CookingThread(self.recipe)
self.cookingThread.start()
並如下更改CookingThread。
class CookingThread(threading.Thread):
def __init__(self, recipe):
super(CookingThread, self).__init__()
self.recipe = recipe
self.stopThread = False
def run(self):
for i in range(self.recipe):
# Check if we should stop the thread
if self.stopThread:
return
else:
print 'Cooking...'
time.sleep(1)
def stop(self):
self.stopThread = True
根據經驗,開發面向對象程序設計時切勿直接訪問字段(例如cookingThread.stopThread
。 嘗試使用諸如stop
的方法進行實際修改。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.