processing python模式_请问:为什么Python自带的Multi-processing模块需要一定时间才能启动?...

我用Python自带的Multi-processing模块做了一个并发的Async的系统。只有2个任务,一快一慢,并发执行,快的等慢的。

import sys, os, time, datetime

from timeit import timeit

import threading

import multiprocessing

from multiprocessing import Pool

def multiprocessor_hack(instance, name, args=(), kwargs=None):

if kwargs is None:

kwargs = {}

return getattr(instance, name)(*args, **kwargs)

class Controller:

request = "Whatever"

def task1(self, request):

print ("Now starting task1 at {}.\n".format(datetime.datetime.now()))

time.sleep(3)

print ("Now finished task1 at {}.\n".format(datetime.datetime.now()))

return "111111"

def task2(self, request):

print ("Now starting task2 at {}.\n".format(datetime.datetime.now()))

time.sleep(10)

print ("Now finished task2 at {}.\n".format(datetime.datetime.now()))

return "222222"

def moderate(self, request):

pool = multiprocessing.Pool(processes = 2)

results = [pool.apply_async(multiprocessor_hack, args = (self, task1', (request,))), pool.apply_async(multiprocessor_hack, args = (self, 'task2', (request,)))]

pool.close()

map (multiprocessing.pool.ApplyResult.wait, results)

response = [r.get() for r in results]

return response

if "__main__" == __name__:

ctrl = Controller()

print ("\nThe pool starts at {}.\n".format(datetime.datetime.now()))

response = ctrl.moderate("Whatever")

print ("\nResponse emerges at {}.".format(datetime.datetime.now()))

print ("\nThe pool ends at {}.".format(datetime.datetime.now()))

运行结果是:

The pool starts at 2018-03-23 15:03:51.187000.

Now starting task1 at 2018-03-23 15:03:51.522000. # 延迟?

Now starting task2 at 2018-03-23 15:03:51.522000. # 延迟?

Now finished the task1 at 2018-03-23 15:03:54.524000.

Now finished the task2 at 2018-03-23 15:04:01.524000.

Response emerges at 2018-03-23 15:04:01.526000.

The pool ends at 2018-03-23 15:04:01.528000.

这里,pool在下午三点 15:03:51.187 开始运行,但是2个任务直到 15:03:51.522 才开始执行!… 请问这里为什么会延迟0.4秒呢?有没有什么办法减小这个延迟?

谢谢了先!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值