【问题标题】:unable to stop thread from a module无法从模块中停止线程
【发布时间】:2016-11-27 19:07:11
【问题描述】:

我需要能够调用正在运行的线程的停止函数。我尝试了几种方法来实现这一目标,但到目前为止还没有运气。我想我需要一个线程 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'

【问题讨论】:

    标签: python multithreading class web2py python-module


    【解决方案1】:

    关于thread 模块,文档是这样说的:

    该模块提供了用于处理多个 线程 [...] threading 模块提供了一个更易于使用和 构建在此模块之上的更高级别的线程 API。

    此外,一旦线程启动,就无法停止或终止线程。 This SO 问题更详细地展示了如何使用threading.Event 来实现可停止线程。

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

    【讨论】:

    • 感谢您的意见!我阅读了文档并尝试使用线程(由于缺乏我的知识和经验而失败)。我遇到了一个与您建议的问题相似的问题。我认为投票最多的答案的顶部是什么对我有用;但是我不知道如何在我的情况下实现它。调用 StoppableThread(threading.Thread) 时我应该将什么作为 arg 传递?
    猜你喜欢
    • 2021-06-28
    • 2021-10-23
    • 1970-01-01
    • 2013-04-18
    • 1970-01-01
    • 2013-05-02
    • 1970-01-01
    • 2012-11-11
    • 1970-01-01
    相关资源
    最近更新 更多