翼度科技»论坛 编程开发 python 查看内容

python进程池中的回调函数

4

主题

4

帖子

12

积分

新手上路

Rank: 1

积分
12
什么是回调函数

指定一个任务后、并且指定一个回调函数后,当指定的进程池执行的任务结束后,会将该任务的返回值作为回调函数的参数传递到回调函数中,并且回调函数得以执行
回调函数在主进程中被执行
  1. import os
  2. from multiprocessing import Pool
  3. def func1(n):
  4.      print('in func1', os.getpid())
  5.      return n * n
  6. def func2(nn):
  7.      print('in func2 %s ' % os.getpid())
  8.      print(nn)
  9. if __name__ == '__main__':
  10.      pool = Pool(4)
  11.      pool.apply_async(func1, args=(10, ), callback=func2)    # calback为回调参数,可以指定一个回调函数,这里指定回调函数为func2
  12.      pool.close()
  13.      pool.join()
  14.      print(os.getpid())
复制代码
10个任务func1投入到含有4个进程的进程池中异步执行,并且指定回调函数为func2,当投入到进程池中的每个任务执行完后,都会将返回值作为参数返回给回调函数,并且回调函数在主进程得以执行
执行了10次func1、10次func2
  1. from multiprocessing import Pool
  2. def func1(n):
  3.     print('in func1')
  4.     return n * n
  5. def func2(nn):
  6.     print('in func2')
  7.     print(nn)
  8. if __name__ == '__main__':
  9.     pool = Pool(4)
  10.     for i in range(10):
  11.         pool.apply_async(func1, args=(10, ), callback=func2)    # calback为回调参数,可以指定一个回调函数,指定进程池执行的任务结束后,会将任务的返回值作为参数传递给回调函数,并执行回调函数,回调函数是在主进程中得以执行的
  12.     pool.close()
  13.     pool.join()
复制代码
一般在爬虫中,用到回调函数比较多,并且是将访问网页、下载网页的过程放到子进程中去做,分析数据,处理数据让回调函数去做,因为访问网页与下载网页有网络延时,而处理数据只占用很小的时间

来源:https://www.cnblogs.com/xxpythonxx/p/17321346.html
免责声明:由于采集信息均来自互联网,如果侵犯了您的权益,请联系我们【E-Mail:cb@itdo.tech】 我们会及时删除侵权内容,谢谢合作!

举报 回复 使用道具