Python:在脚本的后面启动一个线程,并将其返回值赋给一个变量。

26 浏览
0 Comments

Python:在脚本的后面启动一个线程,并将其返回值赋给一个变量。

这个问题已有答案:

如何从线程中获取返回值?

我正在编写一个要求尽可能快的程序。

目前,其中一个函数看起来像这样:

def function():
    value = get_value()
    # Multiple lines of code
    if value == "1":
        print("success")

我想知道是否有一种方法可以在函数开始时调用 get_value() 函数,立即运行多行代码,然后每当 get_value() 函数完成并返回一个值时,值变量就会被更新,准备 if 语句。

谢谢!

admin 更改状态以发布 2023年5月23日
0
0 Comments

这就是期货的用法。使用 concurrent.futures模块,您可以这样做:

import concurrent.futures
# Properly, this would be created once, in a main method, using a with statement
# Use ProcessPoolExecutor instead if the functions involved are CPU bound, rather
# than I/O bound, to work around the GIL
executor = concurrent.futures.ThreadPoolExecutor()
def function():
    value = executor.submit(get_value)
    # Multiple lines of code
    if value.result() == "1":
        print("success")

这创建了一个worker池,您可以将任务提交给它,获得future,当您实际需要结果时可以等待。我建议查看文档中的示例以获得更完整的用法。

另一种方法是使用asyncioasync/await,但这需要完全重写您的代码,不适合短答案的范围。

0