0

我知道这个问题被问了很多时间,但我仍然想知道。

def startMonitor(self,event):       
    selectedInterface = self.interfaces_cblist.GetValue()
    Publisher().sendMessage(("test"),selectedInterface) 
    self.Close()
    selectInterfaceStr = str(selectedInterface) 
    if len(selectedInterface) == 0:
        noSelect_error = wx.MessageDialog(None,"Please select an interface","",wx.OK|wx.ICON_ERROR)
        noSelect_error.ShowModal()
    else:       
        monitorStarted = wx.MessageDialog(None,"Monitor on %s started"%selectInterfaceStr,"",wx.OK|wx.ICON_ERROR)
        monitorStarted.ShowModal()
        self.monitorInterface_button.Disable()
        thread.start_new_thread(self.camtableDetection,(selectInterfaceStr,))
        thread.start_new_thread(self.dhcpexhaustion,(selectInterfaceStr,))

我怎样才能停止线程?

4

1 回答 1

0

您可以有一个分配给变量的 stop 方法,例如self.abort。比,在你正在线程化的函数中,你应该定期检查这个变量并停止函数(使用return或类似的东西)。这是一个使用此技术停止线程的示例类。

class PymineLogger:
    def __init__(self):
        self.file = open('server.log', 'a')
        self.abort = False
        self.log_queue = Queue.Queue()
        threading.Thread(target=self.process_queue, args=()).start()

    def error(self, i):
        line = u'[%s] [ERROR] %s' % (str(time.time()), i)
        self.log_queue.put(line)

    def info(self, i):
        line = u'[%s] [INFO] %s' % (str(time.time()), i)
        self.log_queue.put(line)

    def process_queue(self):
        while not self.abort:
            try:
                log_line = self.log_queue.get(timeout=1)
                print log_line
                self.file.write("%s\n" % log_line)
                self.file.flush()
            except Queue.Empty:
                pass

    def stop(self):
        self.abort = True

stop方法分配变量self.abort ,该变量由线程定期检查。

类源:pymine2项目

于 2013-10-05T14:34:05.367 回答