# 報錯信息
1 PicklingError: Can't pickle <type 'instancemethod'>: attribute lookup __builtin__.instancemethod failed
# 問題原因
# 根據網上資料就是說: multiprocessing 會對調用的函數進行序列號,而類函數不支持 # 備注: 具體原因待查
# 解決方法 —— 類函數不帶返回值
1 # 1. 在類之外定義調用函數 2 def run_class_fun(class_name, msg): 3 class_name.test_func(msg) 4 5 # 2. 修改 apply_async 調用方式 6 pool.apply_async(run_class_fun, args=(self, x, )) 7 # 第一個參數為類外調用函數名 8 # 第二個參數args的第一個參數為 self, 第二個為類函數參數
# 解決方法 —— 類函數帶返回值
1 # 1. 在類之外定義調用函數 2 def run_class_fun(class_name, msg): 3 return class_name.test_func(msg) 4 5 # 2. 修改 apply_async 調用方式 6 res.append(pool.apply_async(run_class_fun, args=(self, x, ))) 7 # 第一個參數為類外調用函數名 8 # 第二個參數args的第一個參數為 self, 第二個為類函數參數
# 全部代碼
1 # -*- coding: utf-8 -*- 2 3 4 import multiprocessing 5 import time 6 7 8 class TestClass(object): 9 def __init__(self): 10 print('init') 11 12 def test_func(self, vm_id): 13 vm_dict = {} 14 cpu_rate = '22.{}'.format(vm_id) 15 mem_rate = '33.{}'.format(vm_id) 16 vm_dict.update({ 17 'vm_id': vm_id, 18 'cpu_rate': cpu_rate, 19 'mem_rate': mem_rate 20 }) 21 return vm_dict 22 23 def run(self): 24 res = [] 25 pool = multiprocessing.Pool(processes=10) 26 for x in range(1, 100): 27 res.append(pool.apply_async(run_class_fun, args=(self, x, ))) 28 pool.close() 29 pool.join() 30 return res 31 32 33 def run_class_fun(class_name, msg): 34 return class_name.test_func(msg) 35 36 37 if __name__ == '__main__': 38 print('----------------START------------------') 39 t1 = time.time() 40 # pool = multiprocessing.Pool(processes=10) 41 # res = [] 42 # for x in range(1, 100): 43 # res.append(pool.apply_async(run_class_fun, args=(TestClass(), x))) 44 # pool.close() 45 # pool.join() 46 tc = TestClass() 47 res = tc.run() 48 print('----------------POOL OVER------------------') 49 print(time.time()-t1) 50 51 vm_infos = [] 52 for r in res: 53 print(r.get()) 54 vm_infos.append(r.get()) 55 56 print(vm_infos) 57 58 print('----------------ALL OVER------------------') 59 print(time.time()-t1)