我想通过python中的模块concurrent.futures使用并行来更新全局变量
事实证明,使用ThreadPoolExecutor可以更新我的全局变量,但是CPU并没有使用它们的所有潜力(总是在5-10%),这是如此缓慢
ProcessPoolExecutor可以使用所有内核( 100%),但我的全局变量不能更新,因为它们不共享相同的全局变量
如何在concurrent.futures模型中使用ProcessPoolExecutor共享我的全局变量。非常感谢你的帮助
发布于 2020-12-20 15:22:18
进程看起来不像使用相同内存空间的线程。所以你需要一些特殊的方法来更新变量。ProcessPoolExecutor
使用multiprocessing
模块,有两种共享数据的方式,共享内存和服务器进程。第一种方式是使用共享内存映射,服务器进程使用Manager
对象来保存共享数据。服务器进程更灵活,共享内存更高效。
使用像ThreadPoolExecutor
这样的服务器进程共享数据,只需将参数传递给您的函数。
def running_proxy(mval):
# consider lock if you need
return mval.value
def start_executor():
with multiprocessing.Manager() as manager:
executor = ProcessPoolExecutor(max_workers=5)
mval = manager.Value('b', 1)
futures = [executor.submit(running_proxy, mval) for _ in range(5)]
results = [x.result() for x in futures]
executor.shutdown()
但是共享内存的方式有一些不同,需要将共享变量设置为全局。
def running_shared():
# consider lock if you need
return sval.value
def set_global(args):
global sval
sval = args
def start_executor():
sval = multiprocessing.Value('b', 1)
# for 3.7+
executor = ProcessPoolExecutor(max_workers=5, initializer=set_global, initargs=(sval,))
# for ~3.6
# set_global(sval)
# executor = ProcessPoolExecutor(max_workers=5)
futures = [executor.submit(running_shared) for _ in range(5)]
results = [x.result() for x in futures]
executor.shutdown()
https://stackoverflow.com/questions/61299918
复制相似问题