如何在python多处理中更新全局变量

时间:2018-01-17 17:39:39

标签: python-3.x

#!/usr/bin/env python
import signal
import time
import sys
import multiprocessing

idx = 0

def worker_function():
    global idx
    idx = idx + 1
    print("idx = {0}\n".format(idx))
    time.sleep(1)


def main():
    for i in range(3):
        worker = multiprocessing.Process(target=worker_function, args=())
        worker.start()
        worker.join()


if __name__ == "__main__":
    main()

输出如下:

idx = 1

idx = 1

idx = 1

问题>为什么每个进程都无法更新python全局变量?

1 个答案:

答案 0 :(得分:1)

每个进程都在更新其全局变量,如输出中所示。否则他们会显示" idx = 0"。如果您想在这些流程之间共享数据,并获得" idx = 1,2,3",那么这是一个完整的故事。请参阅https://docs.python.org/3/library/multiprocessing.html#sharing-state-between-processes