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. 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? 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()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.