我想在多个进程之间共享一个变量。
我读过这篇文章: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
发布于 2022-08-11 21:27:28
成功了:
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()
https://stackoverflow.com/questions/73319023
复制相似问题