【问题标题】:Printing global variable after a multiprocessing join多处理连接后打印全局变量
【发布时间】:2018-10-29 17:14:53
【问题描述】:

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

#!/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:我在 Cygwin 中使用 Python 2.7.14 运行它

【问题讨论】:

  • 您不能在多处理中使用全局变量。

标签: python python-2.7 python-multiprocessing


【解决方案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))

【讨论】:

  • 太棒了!非常感谢
猜你喜欢
  • 1970-01-01
  • 2023-03-15
  • 2011-09-09
  • 1970-01-01
  • 1970-01-01
  • 2021-07-22
  • 2015-11-30
  • 2012-06-28
  • 2011-01-10
相关资源
最近更新 更多