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



我将在多进程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

您需要显式共享内存才能使其正常工作:

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包装器带有自己的锁。

最新更新