小编Ale*_*lex的帖子

谁在使用多处理池的apply_async方法时运行回调?

我正在尝试了解使用多处理池的apply_sync方法时幕后发生的一些事情.

谁运行回调方法?它是调用apply_async的主要进程吗?

假设我发送了一大堆带回调的apply_async命令,然后继续我的程序.当apply_async开始完成时,我的程序仍在执行操作.当主进程仍然忙于脚本时,回调是如何运行我的"主进程"的?

这是一个例子.

import multiprocessing
import time

def callback(x):
    print '{} running callback with arg {}'.format(multiprocessing.current_process().name, x)

def func(x):
    print '{} running func with arg {}'.format(multiprocessing.current_process().name, x)
    return x

pool = multiprocessing.Pool()

args = range(20)

for a in args:
    pool.apply_async(func, (a,), callback=callback)

print '{} going to sleep for a minute'.format(multiprocessing.current_process().name)

t0 = time.time()
while time.time() - t0 < 60:
    pass

print 'Finished with the script'
Run Code Online (Sandbox Code Playgroud)

输出就像是

使用arg 0运行func的PoolWorker-1

PoolWorker-2使用arg 1运行func

PoolWorker-3使用arg 2运行func

MainProcess进入休眠状态< - 主进程正忙

PoolWorker-4使用arg 3运行func

使用arg …

python parallel-processing callback multiprocessing

34
推荐指数
1
解决办法
1万
查看次数

类的实例使用什么资源?

How efficient is python (cpython I guess) when allocating resources for a newly created instance of a class? I have a situation where I will need to instantiate a node class millions of times to make a tree structure. Each of the node objects should be lightweight, just containing a few numbers and references to parent and child nodes.

For example, will python need to allocate memory for all the "double underscore" properties of each instantiated object (e.g. the docstrings, …

python memory-management cpython class instance

14
推荐指数
4
解决办法
500
查看次数

如何通过 multiprocessing.Pool 判断 apply_async 函数是否已启动或者是否仍在队列中

我正在使用 python 的 multiprocessing.Pool 和 apply_async 来调用一堆函数。

如何判断函数是否已开始由池中的成员处理或者是否位于队列中?

例如:

import multiprocessing
import time

def func(t):
    #take some time processing
    print 'func({}) started'.format(t)
    time.sleep(t)

pool = multiprocessing.Pool()

results = [pool.apply_async(func, [t]) for t in [100]*50] #adds 50 func calls to the queue

Run Code Online (Sandbox Code Playgroud)

对于每个AsyncResultin,results您可以调用ready()get(0)来查看 func 是否完成运行。但是如何知道 func 是否 已开始但尚未完成呢?

即对于给定的 AsyncResult 对象(即给定的结果元素),有没有办法查看该函数是否已被调用或者它是否位于池的队列中?

python parallel-processing python-multiprocessing

5
推荐指数
1
解决办法
1237
查看次数