2016-07-24 78 views
0

我需要能够调用正在运行的线程的停止功能。我尝试了几种方法来实现这一目标,但目前为止没有运气。我想我需要一个线程ID,但不知道这是如何完成的。无法停止模块中的线程

相关代码: 型号:

import MODULE 
class do_it(): 
    def __init__(self): 
     self.on_pushButton_start_clicked() 
     return 

    def on_pushButton_start_clicked(self): 
     self.Contr = MODULE.Controller() 
     self.Contr.start() 

    def on_pushButton_stop_clicked(self): 
     if self.Contr: 
      self.Contr.stop() 
      self.Contr = None 
     return 

模块:

import thread 
class Controller(): 
    def __init__(self): 
     self.runme = False 

    def start(self): 
     """Using this to start the controllers eventloop.""" 
     thread.start_new_thread(self._run,()) 

    def stop(self): 
     """Using this to stop the eventloop.""" 
     self.runme = False 

    def _run(self): 
     """The actual eventloop""" 
     self.runme = True 

我想我的问题就出在这里...
我的控制器:

"""I want to use this to control my model, that in turn controls the module""" 

    def start_module(): 
     start=do_it().on_pushButton_start_clicked() 
    return 'Ran start function' 

    def stop_module(): 
     stop=do_it().on_pushButton_stop_clicked() 
    return 'Ran stop function' 

回答

0

关于thread模块,这是文档sa Y:

该模块提供了低级别的原语与多个工作线程 [...]的threading模块提供了一个易于使用和 更高级别的线程API建立在这个模块的顶部。

此外,一旦线程启动,就无法停止或终止线程。 This SO问题进一步详细介绍了如何使用threading.Event来实现可停止的线程。

唯一的区别是daemon thread,当你的主程序存在时它会自动被杀死。

+0

谢谢您的输入!我阅读了文档并尝试使用线程(由于缺乏我的知识和经验,所以不成功)。我遇到了一个类似你问题的问题。我认为最受投票的答案的前半部分是对我有用的东西;但是我不知道如何在我的情况下实现它。调用StoppableThread(threading.Thread)时,我应该如何传递一个arg? – Ivo