自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

Python 獲取線程返回值的三種方式

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

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

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

ret_values = []

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

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

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

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 提供更高級的線程操作,可以直接獲取線程的返回值,相當優(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): # 模擬多個任務
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())

某次運行的結果如下:

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七號
相關推薦

2018-04-02 14:29:18

Java多線程方式

2010-03-12 17:52:35

Python輸入方式

2024-07-01 12:42:58

2022-08-19 11:19:49

單元測試Python

2012-07-17 09:16:16

SpringSSH

2009-07-16 16:23:59

Swing線程

2014-12-31 17:42:47

LBSAndroid地圖

2021-06-24 08:52:19

單點登錄代碼前端

2021-11-05 21:33:28

Redis數據高并發(fā)

2019-11-20 18:52:24

物聯(lián)網智能照明智能恒溫器

2020-11-01 17:10:46

異步事件開發(fā)前端

2024-07-08 09:03:31

2024-09-04 15:56:28

2017-07-14 15:07:23

2009-07-29 09:36:07

無線通信接入方式

2010-09-13 12:19:03

2011-07-25 12:41:38

接入方式布線

2021-11-26 11:07:14

cowsay命令Linux

2023-08-22 07:05:34

PowerShellWindows

2010-08-24 09:43:33

點贊
收藏

51CTO技術棧公眾號