【发布时间】: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