进程并发装饰器

如何使用并发装饰器

# process wrapper
from utils import run_in_async_process

@run_in_async_process
def p():
	print(" i am son proc")

进程并发装饰器

给函数加上这个装饰器,就可以让他作为 独立的 子进程运行

# ************** Concurrent decorator
from multiprocessing import Process,Pipe
from eventlet import spawn,sleep
from functools import wraps

import traceback

def read_msg_from_son_proc(f_conn):
    while True:
        msg_poll = f_conn.poll()
        if msg_poll:
            msg = f_conn.recv()
            if msg :
                raise Exception(msg)
            break
        sleep(0.1)

# func: wrap ,func run in other proc ,
#        and read Except from son proc 
# 
# !!! if you want use it not in dead loop , 
#    please consider , wait for this func
# 
#  beacause this is a async wrapper
#  so it can't wait for return, it just can get Except in son process
def run_in_async_process(f):
    @wraps(f)
    def wrapper(*a,**ka):
        # must be have a conn to send message to father
        def wrap_f(*a,**ka):
            msg =  ""
            conn = ka.pop("conn")
            try:
                f(*a,**ka)
            except:
                msg = "{}\nsome error catch by son proc".format(traceback.format_exc())
            finally:
                conn.send( msg )
                exit(0)
        f_conn,s_conn = Pipe()
        ka.update({"conn":s_conn})
        p = Process(target=wrap_f,args= a , kwargs= ka  )
        p.start()
        x = spawn(read_msg_from_son_proc, f_conn)
        x.wait()
    return wrapper

# *********** end
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

yuemake999

请我喝茶呗

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值