多处理联接后打印全局变量

时间:2018-10-29 17:14:54

标签: python python-2.7 python-multiprocessing

这看起来很简单,但我不明白为什么它不起作用。

#!/usr/bin/env python                        
from multiprocessing import Lock, Process
blah = 0
lock = Lock()

def increment():
    lock.acquire()
    global blah
    blah = blah + 1
    print(blah)
    lock.release()

threads = list()
for i in range(0, 3):
    threads.append(Process(target=increment))

for thread in threads:
    thread.start()

for thread in threads:                       
    thread.join()

print("blah = " + str(blah))

我期望:

1
2
3
blah: 3

但是,我收到了

1
1
1
blah: 0

希望有人能启发我并解释这里发生的事情以及为什么我没有收到我期望的输出。提前致谢! PS:我正在使用Python 2.7.14在Cygwin中运行此程序

1 个答案:

答案 0 :(得分:1)

Python多重处理利用独立的进程,这些进程不共享内存。因此,每个进程都有自己的全局实例。

您将需要改用multiprocessing.Value。

#!/usr/bin/env python                        
from multiprocessing import Process, Value

def increment(blah):
    blah.value = blah.value + 1
    print(blah.value)

if __name__ == '__main__':

    blah = Value('i', 0)
    threads = list()
    for i in range(0, 3):
        threads.append(Process(target=increment, args=[blah]))

    for thread in threads:
        thread.start()

    for thread in threads:                       
        thread.join()

    print("blah = " + str(blah.value))