python多线程获取子线程任务返回值

Posted 程序员同行者

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python多线程获取子线程任务返回值相关的知识,希望对你有一定的参考价值。

今天想实现多线程更新资产信息,所以使用到了threading,但是我需要每个线程的返回值,这就需要我在threading.Thread的基础上进行封装


def auto_asset(node):
    ret = salt.remote_grains_execution_sigle(node)
    asset_info={}
    asset_info[‘os‘]= ret[node][‘oscodename‘]
    asset_info[‘kernelrelease‘]= ret[node][‘kernelrelease‘]
    asset_info[‘cpu_model‘]= ret[node][‘cpu_model‘]
    asset_info[‘dns‘]= ‘,‘.join(ret[node][‘dns‘][‘ip4_nameservers‘])
    asset_info[‘serialnumber‘] =  ret[node][‘serialnumber‘]
    asset_info[‘virtual‘] =  ret[node][‘virtual‘]
    asset_info[‘localhost‘] = ret[node][‘localhost‘]
    asset_info[‘mem_total‘] =  ret[node][‘mem_total‘]
    asset_info[‘num_cpus‘] =  ret[node][‘num_cpus‘]
    asset_info[‘ip4_interfaces‘] = " ".join(ret[node][‘ip4_interfaces‘][‘eth0‘])
    asset_info[‘hwaddr_interfaces‘] = ret[node][‘hwaddr_interfaces‘][‘eth0‘]
    return asset_info

import threading


class MyThread(threading.Thread):

    def __init__(self,func,args=()):
        super(MyThread,self).__init__()
        self.func = func
        self.args = args

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

    def get_result(self):
        try:
            return self.result  # 如果子线程不使用join方法,此处可能会报没有self.result的错误
        except Exception:
            return None

ass =Asset.objects.all()
ids_list =[ i.inner_ip for i in ass]
files = range(len(ids_list))
t_list = []
t_data = []
for i in files:
    t = MyThread(auto_asset, (ids_list[i],))
    t_list.append(t)
    t.start()
for t in t_list:
    t.join()  # 一定要join,不然主线程比子线程跑的快,会拿不到结果
    t_data.append(t.get_result())
    print(t.get_result())

执行结果

{‘localhost‘: ‘VM_75_82_centos‘, ‘hwaddr_interfaces‘: ‘52:54:00:95:fe:c8‘, ‘disks‘: {‘/dev/vda1‘: {‘total‘: ‘49.09G‘, ‘capacity‘: ‘17%‘, ‘avail‘: ‘38.96‘, ‘used‘: ‘7.63‘}}, ‘dns‘: ‘10.236.158.106,10.236.158.114‘, ‘ip4_interfaces‘: ‘10.105.75.82‘, ‘num_cpus‘: 1, ‘serialnumber‘: ‘a1dad25c-8e69-4838-a489-0fe1958e76df‘, ‘os‘: ‘CentOS Linux 7 (Core)‘, ‘mem_total‘: 1839, ‘cpu_model‘: ‘Intel(R) Xeon(R) CPU E5-26xx v4‘, ‘kernelrelease‘: ‘3.10.0-514.26.2.el7.x86_64‘, ‘virtual‘: ‘kvm‘}
{‘localhost‘: ‘wordpress‘, ‘hwaddr_interfaces‘: ‘fa:16:3e:1a:49:72‘, ‘disks‘: {‘/dev/vda1‘: {‘total‘: ‘29.99G‘, ‘capacity‘: ‘12%‘, ‘avail‘: ‘26.54‘, ‘used‘: ‘3.45‘}}, ‘dns‘: ‘103.224.222.222,103.224.222.223,8.8.8.8‘, ‘ip4_interfaces‘: ‘192.168.0.3‘, ‘num_cpus‘: 1, ‘serialnumber‘: ‘c6bce500-113d-11e7-a010-0425c53afb57‘, ‘os‘: ‘CentOS Linux 7 (Core)‘, ‘mem_total‘: 1839, ‘cpu_model‘: ‘Intel Core Processor (Broadwell, IBRS)‘, ‘kernelrelease‘: ‘3.10.0-514.el7.x86_64‘, ‘virtual‘: ‘kvm‘}

以上是关于python多线程获取子线程任务返回值的主要内容,如果未能解决你的问题,请参考以下文章

Python:进程

python获取多线程的返回值

python获取多线程的返回值

python多进程和多线程

Java中使用有返回值的线程

如何使用线程去执行一个 有返回值的方法,并获取返回值?