线程返回值
-
在方法变量中传入全局变量,在方法中对全局变量进行赋值
-
(不堵塞)重新创建一个线程类,将方法写在run的方法中,然后run返回出结果在线程变量中,外部通过方法get到变量的值
import time from threading import Thread def foo(number): time.sleep(20) return number class MyThread(Thread): def __init__(self, number): Thread.__init__(self) self.number = number def run(self): self.result = foo(self.number) def get_result(self): return self.result thd1 = MyThread(3) thd2 = MyThread(5) thd1.start() thd2.start() thd1.join() thd2.join() print(thd1.get_result()) print(thd2.get_result()) 适合于 获取每一个线程的运算结果
-
(阻塞)使用ThreadPoolExecutor的submit
def thread_function(age): return age+1 def run_thread_pool_sub(target, args, max_work_count=3): with ThreadPoolExecutor(max_workers=max_work_count) as t: res = [t.submit(target, i) for i in args] return res if __name__ == '__main__': ages = [1, 3, 4] res = run_thread_pool_sub(thread_function, ages) for future in as_completed(res): data = future.result() print dat 通过future.result()获得结果 submit的返回是无序
-
(阻塞)使用ThreadPoolExecutor的map
def thread_function(age): for i in age: yield i+1 def run_thread_pool(target, args, max_work_count=6): with ThreadPoolExecutor(max_workers=max_work_count) as t: res = t.map(target, args) return res if __name__ == '__main__': ages = [1, 3, 4] # 2222 res = run_thread_pool(target=thread_function, args=(ages,)) for j in res: for i in j: print i map的输出是有序
参考:https://blog.csdn.net/qq_43178297/article/details/102805223
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南