新聞中心
提到線(xiàn)程,你的大腦應(yīng)該有這樣的印象:我們可以控制它何時(shí)開(kāi)始,卻無(wú)法控制它何時(shí)結(jié)束,那么如何獲取線(xiàn)程的返回值呢?今天就分享一下自己的一些做法。

為灤州等地區(qū)用戶(hù)提供了全套網(wǎng)頁(yè)設(shè)計(jì)制作服務(wù),及灤州網(wǎng)站建設(shè)行業(yè)解決方案。主營(yíng)業(yè)務(wù)為成都網(wǎng)站設(shè)計(jì)、網(wǎng)站建設(shè)、灤州網(wǎng)站設(shè)計(jì),以傳統(tǒng)方式定制建設(shè)網(wǎng)站,并提供域名空間備案等一條龍服務(wù),秉承以專(zhuān)業(yè)、用心的態(tài)度為用戶(hù)提供真誠(chéng)的服務(wù)。我們深信只要達(dá)到每一位用戶(hù)的要求,就會(huì)得到認(rèn)可,從而選擇與我們長(zhǎng)期合作。這樣,我們也可以走得更遠(yuǎn)!
方法一:使用全局變量的列表,來(lái)保存返回值
ret_values = []
def thread_func(*args):
...
value = ...
ret_values.append(value)
選擇列表的一個(gè)原因是:列表的 append() 方法是線(xiàn)程安全的,CPython 中,GIL 防止對(duì)它們的并發(fā)訪(fǎng)問(wèn)。如果你使用自定義的數(shù)據(jù)結(jié)構(gòu),在并發(fā)修改數(shù)據(jù)的地方需要加線(xiàn)程鎖。
如果事先知道有多少個(gè)線(xiàn)程,可以定義一個(gè)固定長(zhǎng)度的列表,然后根據(jù)索引來(lái)存放返回值,比如:
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))
方法二:重寫(xiě) Thread 的 join 方法,返回線(xiàn)程函數(shù)的返回值
默認(rèn)的 thread.join() 方法只是等待線(xiàn)程函數(shù)結(jié)束,沒(méi)有返回值,我們可以在此處返回函數(shù)的運(yùn)行結(jié)果,代碼如下:
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()) # 此處會(huì)打印 hello world。
這樣當(dāng)我們調(diào)用 thread.join() 等待線(xiàn)程結(jié)束的時(shí)候,也就得到了線(xiàn)程的返回值。
方法三:使用標(biāo)準(zhǔn)庫(kù) concurrent.futures
我覺(jué)得前兩種方式實(shí)在太低級(jí)了,Python 的標(biāo)準(zhǔn)庫(kù) concurrent.futures 提供更高級(jí)的線(xiàn)程操作,可以直接獲取線(xiàn)程的返回值,相當(dāng)優(yōu)雅,代碼如下:
import concurrent.futures
def foo(bar):
return bar
with concurrent.futures.ThreadPoolExecutor(max_workers=10) as executor:
to_do = []
for i in range(10): # 模擬多個(gè)任務(wù)
future = executor.submit(foo, f"hello world! {i}")
to_do.append(future)
for future in concurrent.futures.as_completed(to_do): # 并發(fā)執(zhí)行
print(future.result())
某次運(yùn)行的結(jié)果如下:
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
本文名稱(chēng):Python獲取線(xiàn)程返回值的三種方式
標(biāo)題網(wǎng)址:http://www.5511xx.com/article/coepcpc.html


咨詢(xún)
建站咨詢(xún)
