Python中获取线程返回值的方式主要有三种:使用全局变量的列表,来保存返回值;重写Thread的join方法,返回线程函数的返回值;使用标准库concurrent.futures,接下来具体为大家介绍一下这三种方式。 1、使用全局变量的列表,来保存返回值 ret_valuese = [] def thread_func(*args): ... value = ... ret_values.append(value) 选择列表的一个原因是:列表的append()方法是线程安全的,CPython中,GIL防止对它们的并发访问。如果你使用自定义的数据结构,在并发修改数据的地方需要加线程锁。 如果事先知道有多少个线程,可以定义一个固定长度的列表,然后根据索引来存放返回值,比如: from = threading import Thread threads = [Nome] * 10 results = [Nome] * 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)) 2、重写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() retirm self._return twrv = ThreadWithReturnValue(target=foo,args=("hello world",)) twrv.start() print(twrv.join())#此处会打印hello world。 这样当我们调用thread.join()等待线程结束的时候,也就得到了线程的返回值。 3、使用标准库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()) |
|
来自: 老男孩IT教育 > 《Python培训》