关于python:Python-获取线程返回值的三种方式

23次阅读

共计 1883 个字符,预计需要花费 5 分钟才能阅读完成。

提到线程,你的大脑应该有这样的印象:咱们能够管制它何时开始,却无法控制它何时完结,那么如何获取线程的返回值呢?明天就分享一下本人的一些做法。

办法一:应用全局变量的列表,来保留返回值

ret_values = []

def thread_func(*args):
    ...
    value = ...
    ret_values.append(value)

抉择列表的一个起因是:列表的 append() 办法是线程平安的,CPython 中,GIL 避免对它们的并发拜访。如果你应用自定义的数据结构,在并发批改数据的中央须要加线程锁。

如果当时晓得有多少个线程,能够定义一个固定长度的列表,而后依据索引来寄存返回值,比方:

from threading import Thread

threads = [None] * 10
results = [None] * 10

def foo(bar, result, index):
    result[index] = f"foo-{index}"

for i in range(len(threads)):
    threads[i] = Thread(target=foo, args=('world!', results, i))
    threads[i].start()

for i in range(len(threads)):
    threads[i].join()

print (" ".join(results))

办法二:重写 Thread 的 join 办法,返回线程函数的返回值

默认的 thread.join() 办法只是期待线程函数完结,没有返回值,咱们能够在此处返回函数的运行后果,代码如下:

from threading import Thread


def foo(arg):
    return arg


class ThreadWithReturnValue(Thread):
    def run(self):
        if self._target is not None:
            self._return = self._target(*self._args, **self._kwargs)

    def join(self):
        super().join()
        return self._return


twrv = ThreadWithReturnValue(target=foo, args=("hello world",))
twrv.start()
print(twrv.join()) # 此处会打印 hello world。

这样当咱们调用 thread.join() 期待线程完结的时候,也就失去了线程的返回值。

办法三:应用规范库 concurrent.futures

我感觉前两种形式切实太低级了,Python 的规范库 concurrent.futures 提供更高级的线程操作,能够间接获取线程的返回值,相当优雅,代码如下:

import concurrent.futures


def foo(bar):
    return bar


with concurrent.futures.ThreadPoolExecutor(max_workers=10) as executor:
    to_do = []
    for i in range(10):  # 模仿多个工作
        future = executor.submit(foo, f"hello world! {i}")
        to_do.append(future)

    for future in concurrent.futures.as_completed(to_do):  # 并发执行
        print(future.result())

某次运行的后果如下:

hello world! 8
hello world! 3
hello world! 5
hello world! 2
hello world! 9
hello world! 7
hello world! 4
hello world! 0
hello world! 1
hello world! 6

以上就是本次分享的所有内容,如果你感觉文章还不错,欢送关注公众号:Python 编程学习圈 ,每日干货分享,发送“J”还可支付大量学习材料,内容笼罩 Python 电子书、教程、数据库编程、Django,爬虫,云计算等等。或是返回编程学习网,理解更多编程技术常识。

正文完
 0