【发布时间】:2018-06-01 03:47:22
【问题描述】:
我在从 python 3 中的线程内运行的子例程中提取返回值时遇到问题。
import threading
from threading import Thread
def dothis():
x = 17
return x
Thread(target = dothis).start()
print(x)
这只是给我一个错误并说 x 未定义,但我从我的子程序中返回了它。谁能指出我正确的方向?
【问题讨论】:
-
一个问题是您根本没有收集返回值。即使没有线程,您也必须将返回值分配给 x 以使 x 具有值,因为 x 仅存在于 dothis 函数的范围内。此外,由于您启动了另一个线程,因此您无法知道 dothis 是否在 print(x) 发生之前完成了执行,因为您根本没有与新线程同步。
-
您可能应该使用队列 - 参见例如this answer 链接的 dup 问题。
标签: python multithreading python-3.x python-multithreading subroutine