Python中获取多线程返回值问题

qq_34621405 qq_34621405 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
现有一个程序,需要打印每个线程的返回值
引用
# -*-coding:utf-8-*-
from time import ctime, sleep
import threading
import numpy as np

loops = ['广州', '北京']
t_list = ['01', '02', '03']
cldas_sum = ['one', 'two', 'three', 'four', 'five', 'six']


class MyThread(object):
def __init__(self, func, args, name=''):
self.name = name
self.func = func
self.args = args

def __call__(self):
self.result = self.func(*self.args)

def get_result(self):
try:
return self.result
except Exception:
return None


def loop(nloop):
global cldas_sum
for j in t_list:
cldas_values = []
for k in range(4):
cldas_value = nloop + str(k)
cldas_values.append(cldas_value)
cldas_values.append(j)
cldas_values.append(nloop)
cldas_sum = np.row_stack((cldas_values, cldas_sum))
print(cldas_sum)
return cldas_sum


def main():
print('start at',ctime())
threads = []
nloops = range(len(loops))
for i in nloops:
t = threading.Thread(target=MyThread(loop, (loops[i],), loop.__name__))
threads.append(t)
for i in nloops: # start threads 此处并不会执行线程,而是将任务分发到每个线程,同步线程。等同步完成后再开始执行start方法
threads[i].start()
for i in nloops: # jion()方法等待线程完成
threads[i].join()
print(threads[i].get_result())
print('DONE AT:', ctime())

if __name__ == '__main__':
main()



前面的洞可以打印出来,在运行到print(threads[i].get_result())时报错,
print(threads[i].get_result())
AttributeError: 'Thread' object has no attribute 'get_result'
get_result方法不是在类中已经写出了吗?请问是哪里出错了
...全文

相关推荐

Python多线程获取返回值代码实例

主要介绍了Python多线程获取返回值代码实例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下

weixin_38546608

python使用threading获取线程函数返回值的实现方法

主要介绍了python使用threading获取线程函数返回值的实现方法,需要的朋友可以参考下

weixin_38646659

python从子线程中获得返回值的方法

今天小编就为大家分享一篇python从子线程中获得返回值的方法,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧

weixin_38712092

Python 多线程+多进程简单使用教程,如何在多进程开多线程

一、Python多进程多线程 关于python多进程多线程的相关基础知识,在我之前的博客有写过,并且就关于python多线程的GIL锁问题,也在我的一篇博客中有相关的解释。 为什么python多线程在面对IO密集型任务的时候会产生加速作用? 为什么python多线程在面对CPU计算密集型任务的时候不仅起不到加速作用,反而加长了计算时间? 相关传送门: 进程,线程,协程关系:https://blog.csdn.net/qq_35869630/article/details/105747155 python线程GIL:https://blog.csdn.net/qq_35869630/articl

weixin_38733367

python继承threading.Thread实现有返回值的子类实例

主要介绍了python继承threading.Thread实现有返回值的子类实例,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧

weixin_38730977
评论 11
收藏 已收藏
分享
返回顶部
qq_34621405
脚本语言 37,737 成员 34,208 内容