小编Fro*_*oor的帖子

Python - 如何实现“可停止”线程?

这里发布一个解决方案来创建一个可停止的线程。但是,我在理解如何实施此解决方案时遇到了一些问题。

使用代码...

import threading

class StoppableThread(threading.Thread):
    """Thread class with a stop() method. The thread itself has to check
    regularly for the stopped() condition."""

    def __init__(self):
        super(StoppableThread, self).__init__()
        self._stop_event = threading.Event()

    def stop(self):
        self._stop_event.set()

    def stopped(self):
        return self._stop_event.is_set()
Run Code Online (Sandbox Code Playgroud)

如何创建一个线程来运行每 1 秒向终端打印一次“Hello”的函数。5 秒后,我使用 .stop() 停止循环函数/线程。

我再次在理解如何实现这个停止解决方案时遇到了麻烦,这是我目前所拥有的。

import threading
import time

class StoppableThread(threading.Thread):
    """Thread class with a stop() method. The thread itself has to check
    regularly for the stopped() condition."""

    def __init__(self):
        super(StoppableThread, self).__init__()
        self._stop_event = threading.Event()

    def stop(self):
        self._stop_event.set()

    def …
Run Code Online (Sandbox Code Playgroud)

multithreading class python-3.x

3
推荐指数
1
解决办法
3995
查看次数

标签 统计

class ×1

multithreading ×1

python-3.x ×1