Python多进程任务创建自定义代理

#!/usr/bin/env python3
# -*- coding: gbk -*-
# @Time      :2019/12/22 20:45

import os
import multiprocessing
from multiprocessing import Manager, Pool
from multiprocessing.managers import BaseManager, BaseProxy


class CodeData:
    function_data = ()


class DataManager(BaseManager):
    pass


class DataProcess:
    def set_proxy(self, func_proxy, task):
        self.func_proxy = func_proxy
        self.task = task

    def sub_process(self):
        for func in self.func_proxy:
            print("task:%s,pid:%s, func:%s\n" % (self.task, os.getpid(), func))


class GeneratorProxy(BaseProxy):
    _exposed_ = ['__iter__', '__next__']

    def __iter__(self):
        return self

    def __next__(self):
        return self._callmethod('__next__')


def get_function_data_proxy(data):
    for func in data:
        yield func


def init_data():
    for i in range(1000):
        CodeData.function_data += (i,)


def multi_process():
    init_data()
    pool = Pool(4, maxtasksperchild=1)
    task_num = 6
    DataManager.register('get_function_data_proxy', get_function_data_proxy, proxytype=GeneratorProxy)
    proxy_list = []
    with DataManager() as manager:
        for task in range(task_num):
            p = manager.get_function_data_proxy(CodeData.function_data)
            proxy_list.append(p)
        for task in range(task_num):
            dp = DataProcess()
            dp.set_proxy(proxy_list[task], task)
            pool.apply_async(dp.sub_process)
        pool.close()
        pool.join()


if __name__ == '__main__':
    multiprocessing.freeze_support()
    multi_process()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值