網(wǎng)站首頁 編程語言 正文
線程,按正常的思路,我們可以控制它何時開始,卻無法控制它何時結(jié)束,那么如何獲取線程的返回值呢?
一、使用全局變量的列表,來保存返回值
ret_values = []
def thread_func(*args):
...
value = ...
ret_values.append(value)
選擇列表的一個原因是:列表的 append() 方法是線程安全的,CPython 中,GIL 防止對它們的并發(fā)訪問。如果你使用自定義的數(shù)據(jù)結(jié)構(gòu),在并發(fā)修改數(shù)據(jù)的地方需要加線程鎖。
如果事先知道有多少個線程,可以定義一個固定長度的列表,然后根據(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()) # 此處會打印 hello world。
這樣當(dāng)我們調(diào)用 thread.join() 等待線程結(jié)束的時候,也就得到了線程的返回值。
三、使用標(biāo)準(zhǔn)庫 concurrent.futures
其實前兩種方式比較低級和直接,Python 的標(biāo)準(zhǔn)庫 concurrent.futures 提供更高級的線程操作,可以直接獲取線程的返回值,相當(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): # 模擬多個任務(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
原文鏈接:https://blog.csdn.net/weixin_39589455/article/details/126954318
- 上一篇:沒有了
- 下一篇:沒有了
相關(guān)推薦
- 2022-03-25 Redis分布式鎖如何實現(xiàn)續(xù)期_Redis
- 2022-11-11 iPhoneX 及以上 手機(jī)底部適配 CSS3方式
- 2022-04-21 C語言中的柔性數(shù)組你真的了解嗎_C 語言
- 2022-11-09 Apifox?Echo學(xué)習(xí)curl?httpie?命令使用詳解_相關(guān)技巧
- 2022-03-27 python內(nèi)置函數(shù)之eval函數(shù)詳解_python
- 2022-09-09 python實現(xiàn)0到1之間的隨機(jī)數(shù)方式_python
- 2023-07-28 dialog 對話框垂直居中
- 2022-10-06 Iptables防火墻自定義鏈表實現(xiàn)方式_安全相關(guān)
- 欄目分類
-
- 最近更新
-
- window11 系統(tǒng)安裝 yarn
- 超詳細(xì)win安裝深度學(xué)習(xí)環(huán)境2025年最新版(
- Linux 中運(yùn)行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎(chǔ)操作-- 運(yùn)算符,流程控制 Flo
- 1. Int 和Integer 的區(qū)別,Jav
- spring @retryable不生效的一種
- Spring Security之認(rèn)證信息的處理
- Spring Security之認(rèn)證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權(quán)
- redisson分布式鎖中waittime的設(shè)
- maven:解決release錯誤:Artif
- restTemplate使用總結(jié)
- Spring Security之安全異常處理
- MybatisPlus優(yōu)雅實現(xiàn)加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務(wù)發(fā)現(xiàn)-Nac
- Spring Security之基于HttpR
- Redis 底層數(shù)據(jù)結(jié)構(gòu)-簡單動態(tài)字符串(SD
- arthas操作spring被代理目標(biāo)對象命令
- Spring中的單例模式應(yīng)用詳解
- 聊聊消息隊列,發(fā)送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠(yuǎn)程分支