首頁  >  文章  >  後端開發  >  Python 取得線程傳回值的三種方式

Python 取得線程傳回值的三種方式

WBOY
WBOY轉載
2023-04-13 10:43:092109瀏覽

提到線程,你的大腦應該有這樣的印象:我們可以控制它何時開始,卻無法控制它何時結束,那麼如何取得線程的回傳值呢?今天就分享一下自己的一些做法。

方法一:使用全域變數的列表,來保存傳回值

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 取得線程傳回值的三種方式的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:51cto.com。如有侵權,請聯絡admin@php.cn刪除