繁体   English   中英

为什么使用Python的多处理模块似乎没有按顺序处理?

[英]Why does this use of Python's multiprocessing module not seem to process sequentially?

我正在尝试学习使用Python的Multiprocessing模块。 作为第一个测试,我想我将同时运行四个15秒的过程。 我写了这个模块,叫做“ multiPtest.py”:

import time
import timeit
import multiprocessing


def sleepyMe(napTime):
    time.sleep(napTime)
    print "Slept %d secs" % napTime

def tester(numTests):
    #Launch 'numTests' processes using multiProcessing module
    for _ in range(numTests):
        p = multiprocessing.Process(target=sleepyMe(15))
        p.start() #Launch an 'independent' process
        #p.join() ##Results identical with or without join

def multiTester():
    #Time running of 4 processes
    totTime = timeit.Timer('tester(4)', setup = 'from multiPtest import     tester').repeat(1,1)
    print "Total = ", totTime[0]

但是,当我跑步时,会得到以下结果:

Python 2.7.6 (default, Mar 22 2014, 22:59:56) 
[GCC 4.8.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from multiPtest import *
>>> multiTester()
Slept 15 secs
Slept 15 secs
Slept 15 secs
Slept 15 secs
Total =  60.0739970207

我本来希望总时间接近15秒,而不是60秒。我知道我有4个内核,因为我查看了/ proc / cpuinfo:

~/Projects/PythonProjects$ cat /proc/cpuinfo 
processor   : 0
vendor_id   : GenuineIntel
cpu family  : 6 
model       : 60
model name  : Intel(R) Core(TM) i7-4900MQ CPU @ 2.80GHz
stepping    : 3
microcode   : 0x17
cpu MHz     : 800.000
cache size  : 8192 KB
physical id : 0
siblings    : 8
core id     : 0
cpu cores   : 4
...

为什么我看不到这四个卧铺同时入睡? 在其他人处于睡眠/忙碌状态时,我是否应该能够创建和启动新流程? 我是否误解了有关多处理,Python的多处理模块或其他方面的东西?

在行中

p = multiprocessing.Process(target=sleepyMe(15))

您实际上已经调用了 sleepyMe并将结果( None )用作target参数的值,因此等待15秒。 尝试

p = multiprocessing.Process(target=sleepyMe, args=(15, ))

并将函数修改为for循环之后的 join()所有子进程,否则它将立即返回,并且最终总时间接近于零。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM