# -*- coding: UTF-8 --
from multiprocessing import Process,Manager,Lock,Pool
要在调用进程池执行的函数
def sayHi(num):
print "def print result:",num进程池最大运行数
p = Pool(processes=4)模拟并发调用线程池
for i in range(10):
p.apply_async(sayHi,[i])
# -- coding: UTF-8 --
from multiprocessing import Process,Manager,Lock,Pool
def sayHi(num):
return num*num
p = Pool(processes=4)申明一个列表,用来存放各进程返回的结果
result_list =[]
for i in range(10):
result_list.append(p.apply_async(sayHi,[i])) #将返回结果append到列表中
循环读出列表返回的结果
for res in result_list:
print "the result:",res.get()
注:get()函数得出每个返回结果的值
执行结果:
[root@python thread]# python pool.py
the result: 0
the result: 1
the result: 4
the result: 9
the result: 16
the result: 25
the result: 36
the result: 49
the result: 64
the result: 81
[root@python thread]# python pool.py
the result: 0
the result: 1
the result: 4
the result: 9
the result: 16
the result: 25
the result: 36
the result: 49
the result: 64
the result: 81
[root@python thread]# python pool.py
the result: 0
the result: 1
the result: 4
the result: 9
the result: 16
the result: 25
the result: 36
the result: 49
the result: 64
# -- coding: UTF-8 --
from multiprocessing import Process,Manager,Lock,Pool
def sayHi(num):
return num*num
p = Pool(processes=4)申明一个列表,用来存放各进程返回的结果
result_list =[]
for i in range(10):
result_list.append(p.apply_async(sayHi,[i])) #将返回结果append到列表中
p.close()
p.join() #调用join之前,先调用close函数,否则会出错。执行完close后不会有新的进程加入到pool,join函数等待所有子进程结束循环读出列表返回的结果
for res in result_list:
print "the result:",res.get()