如下将实现一个简单的多进程,异步的,并发机制:
1. 一些初始定义
import multiprocessing
aaa = [] # 多个进程公用的公共变量(用于多个进程同时要处理的那个变量)
# 将用于多进程分布式散开的一个原本list (for遍历将做12次)
test_list = [3,4,5,6,7,8,9,10,11,12,13,14]
# 并发进程数(也就是上面的只做4次了)
processesNum = 3
# 每一个进程将处理4个
loopNum = len(test_list) / processesNum
2. 定义实现的函数
# 要实现的核心功能
def get_info(lit, ccc):
bbb = []
for ii in lit:
x = ii * 2 + ccc
print x
bbb.append(x)
return bbb
# callback处理:即多进程中有retrun值的情况
def process_callback_info(res):
global aaa
aaa.append(res)
print aaa
3. 实现多进程处理
pool = multiprocessing.Pool(processes=processesNum)
ccc = 3
for i in range(processesNum):
if i < processesNum - 1:
lit = test_list[loopNum * i:loopNum * (i + 1)]
else:
lit = test_list[loopNum * i:]
print 'start pool %d,hotelList is %d' % (i, len(lit))
pool.apply_async(get_info, args=(lit, ccc), callback=process_callback_info)
# pool.apply(get_info, (lit,))
pool.close()
pool.join()
4 运行结果: