gpt4 book ai didi

python - 如何在 Python 中使用 multiprocessing.pool 创建全局锁/信号量?

转载 作者:太空狗 更新时间:2023-10-29 17:40:46 27 4
gpt4 key购买 nike

我想限制子进程中的资源访问。例如 - 限制 http 下载磁盘 io 等。我怎样才能实现扩展这个基本代码?

请分享一些基本的代码示例。

pool = multiprocessing.Pool(multiprocessing.cpu_count())
while job_queue.is_jobs_for_processing():
for job in job_queue.pull_jobs_for_processing:
pool.apply_async(do_job, callback = callback)
pool.close()
pool.join()

最佳答案

创建池时使用 initializer 和 initargs 参数,以便在所有子进程中定义全局。

例如:

from multiprocessing import Pool, Lock
from time import sleep

def do_job(i):
"The greater i is, the shorter the function waits before returning."
with lock:
sleep(1-(i/10.))
return i

def init_child(lock_):
global lock
lock = lock_

def main():
lock = Lock()
poolsize = 4
with Pool(poolsize, initializer=init_child, initargs=(lock,)) as pool:
results = pool.imap_unordered(do_job, range(poolsize))
print(list(results))

if __name__ == "__main__":
main()

此代码将按升序(作业提交的顺序)打印出数字 0-3,因为它使用了锁。注释掉 with lock: 行以查看它按降序打印出数字。

此解决方案适用于 Windows 和 Unix。然而,因为进程可以在 unix 系统上进行 fork,所以 unix 只需要在模块范围内声明全局变量。子进程获得父进程内存的副本,其中包括仍然有效的锁对象。因此,初始化程序并不是严格需要的,但它可以帮助记录代码的预期工作方式。当 multiprocessing 能够通过 fork 创建进程时,以下内容也有效。

from multiprocessing import Pool, Lock
from time import sleep

lock = Lock()

def do_job(i):
"The greater i is, the shorter the function waits before returning."
with lock:
sleep(1-(i/10.))
return i

def main():
poolsize = 4
with Pool(poolsize) as pool:
results = pool.imap_unordered(do_job, range(poolsize))
print(list(results))

if __name__ == "__main__":
main()

关于python - 如何在 Python 中使用 multiprocessing.pool 创建全局锁/信号量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28664720/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com