Today I want to implement multi-threaded update asset information, so used to threading, but I need the return value of each thread, which requires me in threading. The thread is encapsulated on the basis of
def auto_asset (node): ret = salt.remote_grains_execution_sigle (node) asset_info={} asset_info[' os ']= ret[node][' O Scodename '] 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][' Serialnu Mber '] 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_infoimport threadingclass MyThread (threading. Thread): Def __init__ (self,func,args= ()): Super (Mythread,self). __init__ () Self.func = Func self.ar GS = args def run (self): Self.result = Self.func (*self.args) def get_resUlt (self): Try:return Self.result # If the child thread does not use the Join method, there may be no Self.result error reported here except Exception: return Noneass =asset.objects.all () ids_list =[i.inner_ip for i in ass]files = Range (len (ids_list)) t_list = []t_da TA = []for i in files:t = MyThread (Auto_asset, (Ids_list[i],)) T_list.append (t) T.start () for T in T_LIST:T.J Oin () # must join, otherwise the mainline Cheng thread runs fast, will not get results t_data.append (T.get_result ()) print (T.get_result ())
Execution Results
{' 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 Process or (Broadwell, Ibrs) ', ' kernelrelease ': ' 3.10.0-514.el7.x86_64 ', ' virtual ': ' KVM '}
Python multithreading gets the child thread task return value