Python 线程不是 alive/finished 运行 但尚未返回值

Python thread is not alive/finished running but value is not returned yet

我有一个 class FrameThread 继承自 python

中的 Thread
class FrameThread(Thread):
def __init__(self, threadID, customFunction, args):
    threading.Thread.__init__(self)
    self.threadID = threadID
    self.task = customFunction
    self.args = args
    self.output = None

def run(self):
    self.output = self.task(self.args)

我有这个 class 的原因是一旦线程完成 运行 我的自定义函数(通过调用 is_alive() 检查),我可以检索函数返回值.

我的程序看起来像这样

第一段代码

mythread = FrameThread(threadID, myCustomFunction, args)
mythread.start()

在第二个代码块

if not mythread.is_alive():
   outputVar = mythread.output
   print(outputVar)

这有时有效,有时无效。控制台打印出 myCustomFunction 的实际返回值或 None。所以我认为这可能是因为在 python 运行 'outputVar = mythread.output' 之前没有将值传递给 mythread.output。所以我在第二个代码块中添加了一个循环只是为了测试。

if not mythread.is_alive():
   while mythread.output == None:
      print("Reee")
   outputVar = mythread.output
   print(outputVar)

令我惊讶的是,程序打印出一堆“Reee”,然后打印出正确的 outputVar 值。

这种行为很奇怪,可能是因为我做错了什么(很可能在我的 FrameThread class 中)。请告诉我如何修复它,或者如何正确实现 FrameThread subclass。

我检查了 threading 模块的代码,但找不到发生这种情况的原因。不过,如果在获得结果之前 join 线程,则可以解决此问题。你 应该 无论如何 join 在某个时候的线程。您应该将第二个代码块替换为:

if not mythread.is_alive():
   mythread.join()
   outputVar = mythread.output
   print(outputVar)

像这样使用 is_alive() 很少有用:它主要用于检查 join 是否超时。例如:

mythread.join(0)
if mythread.is_alive():
   # timed out
   print('Still waiting for thread to finish...')
   # do some work in the main thread...
else:
   outputVar = mythread.output
   print(outputVar)

我建议您考虑使用其他类型的同步或concurrent.futures