首页 > 解决方案 > 如何获取在类内运行的任务的当前状态

问题描述

我有一个做很多事情的类,在那个类中我有一个需要一些时间才能完成的函数。获取该功能当前正在执行的“状态”的最佳方法是什么?线程是一个解决方案还是我应该启动一个进程或其他什么?

我正在尝试做的事情:

import threading
import time

class Work:
    def __init__(self):
        self.status = "created"

    def get_status(self):
        return self.status

    def slowFunction(self):
        self.status = "slowFunction started working"    
        time.sleep(300)
        self.status = "did some work"
        time.sleep(300)
        self.status = "slowFunction finished"
    
    #a lot more things here
    #...    

if __name__ == "__main__":
    obj = Work()
    t = threading.Thread(target=obj.slowFunction())
    t.start()

    while obj.get_status() != "slowFunction finished"
        print obj.get_status()
        time.sleep(5)

我希望循环在启动线程后立即启动,它目前正在等待 slowFunction 完成。

标签: pythonmultithreadingpython-multithreadingconcurrent.futures

解决方案


slowFunction作为线程目标传递时删除括号。

t = threading.Thread(target=obj.slowFunction)

推荐阅读