# -*- coding: utf-8 -*-
import os
import time
from multiprocessing import Pool
def func(n):
print("%s子进程(%s)" % (n, os.getpid()))
time.sleep(0.5)
return n**2
def handle(ret):
print("%s回调函数<%s>" % (ret, os.getpid()))
if __name__ == '__main__':
pool = Pool() # 进程池里默认开启os.cpu_count()个进程
for i in range(6):
pool.apply_async(func, args=(i,), callback=handle) # 异步执行
pool.close() # 进程池不再接受新任务
pool.join() # 进程池里的进程执行完了
print("主进程%s" % os.getpid())
# 0子进程(6456)
# 1子进程(7416)
# 2子进程(7536)
# 3子进程(6992)
# 4子进程(6456)
# 0回调函数<4624>
# 1回调函数<4624>
# 5子进程(7416)
# 4回调函数<4624>
# 9回调函数<4624>
# 16回调函数<4624>
# 25回调函数<4624>
# 主进程4624
#注意:
# 子进程是耗时的任务,回调函数是主进程执行的.
#回调函数在写的时候注意一点,回调函数的形参执行有一个,如果你的执行函数有多个返回值,那么也可以被回调
# 函数的这一个形参接收,接收的是一个元祖,包含着你执行函数的所有返回值。
使用多个进程来请求多个url来减少网络等待时间
# coding:utf-8
import os
import json
import requests
from multiprocessing import Pool
def get_url_content(url):
print("[%s] %s" % (os.getpid(), url))
response = requests.get(url)
if response.status_code == 200:
return {'url': response.content.decode("utf-8")}
def write_file(dic):
with open("request.json", "a", encoding="utf-8") as f:
json.dump(dic, f, ensure_ascii=False)
f.write("
")
if __name__ == '__main__':
url_lst = [
'https://www.baidu.com',
'https://www.python.org',
'https://www.openstack.org',
'https://help.github.com/',
'http://www.sina.com.cn/'
]
pool = Pool(5)
for url in url_lst:
pool.apply_async(get_url_content, args=(url,), callback=write_file)
pool.close()
pool.join()
无需回调函数实例
# coding:utf-8
import time
from multiprocessing import Pool
def work(n):
time.sleep(1)
return n**2
if __name__ == '__main__':
p = Pool()
res_l = []
for i in range(10):
res = p.apply_async(work, args=(i,))
res_l.append(res)
p.close()
p.join() # 等待进程池中所有进程执行完毕
print([re.get() for re in res_l]) # 主进程拿到所有的处理结果,可以在主进程中进行统一进行处理
# [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]