IT评测·应用市场-qidao123.com
标题:
python进程池中的回调函数
[打印本页]
作者:
鼠扑
时间:
2023-4-15 16:06
标题:
python进程池中的回调函数
什么是回调函数
指定一个任务后、并且指定一个回调函数后,当指定的进程池执行的任务结束后,会将该任务的返回值作为回调函数的参数传递到回调函数中,并且回调函数得以执行
回调函数在主进程中被执行
import os
from multiprocessing import Pool
def func1(n):
print('in func1', os.getpid())
return n * n
def func2(nn):
print('in func2 %s ' % os.getpid())
print(nn)
if __name__ == '__main__':
pool = Pool(4)
pool.apply_async(func1, args=(10, ), callback=func2) # calback为回调参数,可以指定一个回调函数,这里指定回调函数为func2
pool.close()
pool.join()
print(os.getpid())
复制代码
10个任务func1投入到含有4个进程的进程池中异步执行,并且指定回调函数为func2,当投入到进程池中的每个任务执行完后,都会将返回值作为参数返回给回调函数,并且回调函数在主进程得以执行
执行了10次func1、10次func2
from multiprocessing import Pool
def func1(n):
print('in func1')
return n * n
def func2(nn):
print('in func2')
print(nn)
if __name__ == '__main__':
pool = Pool(4)
for i in range(10):
pool.apply_async(func1, args=(10, ), callback=func2) # calback为回调参数,可以指定一个回调函数,指定进程池执行的任务结束后,会将任务的返回值作为参数传递给回调函数,并执行回调函数,回调函数是在主进程中得以执行的
pool.close()
pool.join()
复制代码
一般在爬虫中,用到回调函数比较多,并且是将访问网页、下载网页的过程放到子进程中去做,分析数据,处理数据让回调函数去做,因为访问网页与下载网页有网络延时,而处理数据只占用很小的时间
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!
欢迎光临 IT评测·应用市场-qidao123.com (https://dis.qidao123.com/)
Powered by Discuz! X3.4