我想使用ProcessPoolExecutor
的共享状态
代码:
from multiprocessing import Value
from concurrent.futures import ProcessPoolExecutor
def function(times, a):
print('I'm here')
for _ in range(times):
with a.get_lock():
a.value += 1
def main():
a = Value('I', 0, lock=True)
with ProcessPoolExecutor(max_workers=5) as executor:
for i in range(5):
executor.submit(function, 1000000, a)
print("----------------------", a.value)
main()
但它卡住了,甚至没有打印出"我在这里">
您需要将共享变量设置为全局变量,而不是传递参数。
from multiprocessing import Value
from concurrent.futures import ProcessPoolExecutor
def function(times):
print('I'm here')
for _ in range(times):
with a.get_lock():
a.value += 1
def set_global(args):
global a
a = args
def main():
a = Value('I', 0, lock=True)
set_global(a)
with ProcessPoolExecutor(max_workers=5) as executor:
for i in range(5):
executor.submit(function, 1000000)
print("----------------------", a.value)
if __name__ == '__main__':
main()