2014-03-13 82 views
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) 

回答

1

的問題是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這樣的方法實際進行修改。