首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >多处理中的变量共享与Python?(ProcessPoolExecutor())

多处理中的变量共享与Python?(ProcessPoolExecutor())
EN

Stack Overflow用户
提问于 2022-08-11 10:17:12
回答 1查看 101关注 0票数 0

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

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

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

代码语言:javascript
运行
复制
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()

它给了我错误:

代码语言:javascript
运行
复制
printshare name 'x' is not defined
EN

Stack Overflow用户

发布于 2022-08-11 21:27:28

成功了:

代码语言:javascript
运行
复制
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()
票数 0
EN
查看全部 1 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/73319023

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档