1. 程式人生 > >python多線程獲取子線程任務返回值

python多線程獲取子線程任務返回值

rgs init range proc imp nod super roc exceptio

今天想實現多線程更新資產信息,所以使用到了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多線程獲取子線程任務返回值