gpt4 book ai didi

python - 如何在不同的进程python中增加计数器?

转载 作者:太空宇宙 更新时间:2023-11-03 10:50:02 24 4
gpt4 key购买 nike

我要在多进程python中增加start全局变量,

来源:

from multiprocessing import Process, Lock

start = 0

def printer(item, lock):
"""
Prints out the item that was passed in
"""
global start
lock.acquire()
try:
start = start + 1
print(start)
finally:
lock.release()

if __name__ == '__main__':
lock = Lock()
items = ['tango', 'foxtrot', 10]
for item in items:
p = Process(target=printer, args=(item, lock))
p.start()

输出:

1
1
1

我为 start 计数器使用了锁,但它不起作用,我期待看到这个输出:

1 # ==> start = 1
2 # ==> start = start + 1 = 2
3 # ==> start = start + 1 = 3

最佳答案

您需要explicitly share the memory使其正常工作:

from multiprocessing import Process, Lock, Value

start = Value('I',0)

def printer(item):
"""
Prints out the item that was passed in
"""
with start.get_lock():
start.value+=1
print(start.value)

请注意,多处理 Value 包装器带有自己的锁。

关于python - 如何在不同的进程python中增加计数器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52517320/

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