[英]Variable sharing in Multiprocessing with Python? (ProcessPoolExecutor())
I want to share a variable among multiple processes.我想在多个进程之间共享一个变量。
I read this one: Shared variable in concurrent.futures.ProcessPoolExecutor() python but it didn't really help my code.我读了这个: Shared variable in concurrent.futures.ProcessPoolExecutor() python但它并没有真正帮助我的代码。 I am also not an expert in this and just starting since a few weeks (first year student):)我也不是这方面的专家,几周后才开始(一年级学生):)
How is is possible to share the variable x among (all) threads as soon as it becomes available?一旦变量x可用,如何在(所有)线程之间共享它? This is what I have so far:这是我到目前为止所拥有的:
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()
And it gives me the error:它给了我错误:
printshare name 'x' is not defined
Got it to work:让它工作:
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.