0
我有一個對象cooker
,它的run()
方法啓動一個新線程cookingThread
。 5秒後,如何通過設置變量stopThread
來停止cookingThread
?在正在運行的線程內設置變量以停止線程
嘗試使用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)