繁体   English   中英

使用 Python 在多处理中共享变量? (ProcessPoolExecutor())

[英]Variable sharing in Multiprocessing with Python? (ProcessPoolExecutor())

我想在多个进程之间共享一个变量。

我读了这个: Shared variable in concurrent.futures.ProcessPoolExecutor() python但它并没有真正帮助我的代码。 我也不是这方面的专家,几周后才开始(一年级学生):)

一旦变量x可用,如何在(所有)线程之间共享它? 这是我到目前为止所拥有的:

import concurrent.futures, time

def share():
    time.sleep(1)
    global x
    x = "hello!"

def printshare():
    while True:
        time.sleep(0.5)
        try:
            print(x)
        except Exception as e:
            print(f"printshare {e}")

def main():
    with concurrent.futures.ProcessPoolExecutor() as executor:    
        executor.submit(share)
        executor.submit(printshare)

if __name__ == '__main__':
    main()

它给了我错误:

printshare name 'x' is not defined

让它工作:

def foo(x):
    time.sleep(1)
    x.string = 'hello'


def foo2(x):
    time.sleep(1.5)
    print(x.string)

def main():
    x = Value('i')

    with concurrent.futures.ProcessPoolExecutor() as executor:    
        executor.submit(foo(x))
        executor.submit(foo2(x))

if __name__ == '__main__':
    main()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM