溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

Python獲取線程返回值的方式有哪些

發(fā)布時(shí)間:2023-04-13 11:01:55 來源:億速云 閱讀:82 作者:iii 欄目:編程語言

這篇文章主要講解了“Python獲取線程返回值的方式有哪些”,文中的講解內(nèi)容簡(jiǎn)單清晰,易于學(xué)習(xí)與理解,下面請(qǐng)大家跟著小編的思路慢慢深入,一起來研究和學(xué)習(xí)“Python獲取線程返回值的方式有哪些”吧!

方法一:使用全局變量的列表,來保存返回值
ret_values = []

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

選擇列表的一個(gè)原因是:列表的 append() 方法是線程安全的,CPython 中,GIL 防止對(duì)它們的并發(fā)訪問。如果你使用自定義的數(shù)據(jù)結(jié)構(gòu),在并發(fā)修改數(shù)據(jù)的地方需要加線程鎖。

如果事先知道有多少個(gè)線程,可以定義一個(gè)固定長(zhǎng)度的列表,然后根據(jù)索引來存放返回值,比如:

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 方法,返回線程函數(shù)的返回值

默認(rèn)的 thread.join() 方法只是等待線程函數(shù)結(jié)束,沒有返回值,我們可以在此處返回函數(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() 等待線程結(jié)束的時(shí)候,也就得到了線程的返回值。

方法三:使用標(biāo)準(zhǔn)庫(kù) concurrent.futures

我覺得前兩種方式實(shí)在太低級(jí)了,Python 的標(biāo)準(zhǔn)庫(kù) concurrent.futures 提供更高級(jí)的線程操作,可以直接獲取線程的返回值,相當(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

感謝各位的閱讀,以上就是“Python獲取線程返回值的方式有哪些”的內(nèi)容了,經(jīng)過本文的學(xué)習(xí)后,相信大家對(duì)Python獲取線程返回值的方式有哪些這一問題有了更深刻的體會(huì),具體使用情況還需要大家實(shí)踐驗(yàn)證。這里是億速云,小編將為大家推送更多相關(guān)知識(shí)點(diǎn)的文章,歡迎關(guān)注!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI