Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/306.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 当我使用multiprocessing.pool.apply\u async的次数超过我使用处理器的次数时会发生什么_Python_Multiprocessing_Python 3.3_Asynchronous - Fatal编程技术网

Python 当我使用multiprocessing.pool.apply\u async的次数超过我使用处理器的次数时会发生什么

Python 当我使用multiprocessing.pool.apply\u async的次数超过我使用处理器的次数时会发生什么,python,multiprocessing,python-3.3,asynchronous,Python,Multiprocessing,Python 3.3,Asynchronous,我有以下设置: results = [f(args) for _ in range(10**3)] 但是,f(args)需要很长时间来计算。所以我想对它进行多重处理。我想这样做: pool = mp.pool(mp.cpu_count() -1) # mp.cpu_count() -> 8 results = [pool.apply_async(f, args) for _ in range(10**3)] 很明显,我的电脑上没有1000个处理器,所以我担心: 上面的调用是否会导致10

我有以下设置:

results = [f(args) for _ in range(10**3)]
但是,
f(args)
需要很长时间来计算。所以我想对它进行多重处理。我想这样做:

pool = mp.pool(mp.cpu_count() -1) # mp.cpu_count() -> 8
results = [pool.apply_async(f, args) for _ in range(10**3)]
很明显,我的电脑上没有1000个处理器,所以我担心:
上面的调用是否会导致1000个进程同时竞争CPU时间,还是同时运行7个进程,在上一个调用完成时迭代计算下一个
f(args)


我想我可以做一些类似于
pool.async\u-map(f,(args表示范围(10**3))
的事情来获得相同的结果,但本文的目的是理解
池的行为。apply\u async

工作进程的数量完全由
mp.pool()
的参数控制。因此,如果
mp.cpu\u count()
在框中返回8,将创建7个工作进程

所有
pool
方法(
apply_async()
)使用的工作进程数都不会超过这么多。在封面下,参数在主程序中被pickle,并通过进程间管道发送到工作进程。这个隐藏的机制有效地创建了一个工作队列,固定数量的工作进程从中提取工作描述(函数名+参数)


除此之外,这一切都只是魔术;-)

您的池中运行的进程数永远不会超过工作进程数(在您的情况下,
mp.cpu\u count()-1
。如果调用
apply\u async
,并且所有工作进程都很忙,工作进程一释放,任务就会排队执行。您可以通过一个简单的测试程序看到这一点:

#!/usr/bin/python

import time
import multiprocessing as mp

def worker(chunk):
    print('working')
    time.sleep(10)
    return

def main():
    pool = mp.Pool(2)  # Only two workers
    for n in range(0, 8):
        pool.apply_async(worker, (n,))
        print("called it")
    pool.close()
    pool.join()

if __name__ == '__main__':
    main()
输出如下:

called it
called it
called it
called it
called it
called it
called it
called it
working
working
<delay>
working
working
<delay>
working 
working
<delay>
working
working
称之为
叫它
叫它
叫它
叫它
叫它
叫它
叫它
工作
工作
工作
工作
工作
工作
工作
工作

我复制并粘贴了上面的代码,脚本只打印了8个“called it”,然后就停止了。这是什么原因呢?我使用的是python 2.7。@qkhhly我已经非常晚了,但是示例代码中有一个bug(使用
n
作为
应用异步
的参数,当它应该是
(n,)
).刚刚修好。