python3 进程池回调函数

# -*- 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("\n")


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]

 

转载于:https://www.cnblogs.com/lilyxiaoyy/p/10987310.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值