python - 使用线程时避免使用样板。线程

标签 python

class MyThread(threading.Thread):

    def __init__(self):
        threading.Thread.__init__(self)
        self._finished = False
        self._end = False
        self._running = False

    def run(self):
        self._running = True
        while not self._finished:
            time.sleep(0.05) 
        self._end = True

    def stop(self):
        if not self._running:
            return 

        self._finished = True
        while not self._end:
            time.sleep(0.05)

我希望有一个可以调用 run() 和 stop() 的线程。 stop 方法应该等待 run 有序完成。如果 run 甚至没有被调用,我也希望 stop 没有任何问题地返回。我该怎么做?

我在测试环境中的 setup() 方法中创建了这个线程,并在teardown() 中对其运行停止。但是,在某些测试中我不调用 run()。

更新

这是我的第二次尝试。现在正确吗?

import threading
import time
class MyThread(threading.Thread):

    def __init__(self):
        threading.Thread.__init__(self)
        self._finished = False

    def run(self):
        while not self._finished:
            print("*")
            time.sleep(1) 
        print("Finished Other")

    def finish(self):
        self._finished = True
        self.join()     


m = MyThread()
m.start()
print("After")
time.sleep(5)
m.finish()
print("Finished Main")

最佳答案

您不需要也不应该自己实现这一点。您正在寻找的东西已经存在,至少在很大程度上是存在的。然而,它不被称为“停止”。您描述的概念通常称为“加入”。

查看连接文档:https://docs.python.org/3.4/library/threading.html#threading.Thread.join

你写

The stop method should wait for run to complete in an orderly manner.

Join 的文档说:“等待线程终止。” 检查 ✓

你写

I also want stop to return without any issues if run hasn't even be called

Join 的文档说:“在线程启动之前 join() 也是一个错误”

因此,您唯一需要确保的是,仅在通过 start() 方法启动线程后才调用 join()。这对你来说应该很容易。

关于python - 使用线程时避免使用样板。线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28092693/

相关文章:

python - Python + Redland 用于 RDF 存储和检索的示例

python - 正确写一个numpy meshgrid的函数

python - 如何防止python中的ValueError

python - 函数返回 'None'

python - Eclipse 和 PyDev 调试器出现错误,但该程序在 win 7 上运行良好

python - Plotly:如何绘制累积的 "steps"直方图?

python - 如何重新格式化此 json 以进行数据库导入?

python - 删除以 @ 开头的每行的最后一个字符

python - 引导测试和使用 Python 测试发现

python - 列表理解中奇怪的 lambda 行为