Can't access global variable in python -
i'm using multi processing library in python in code below:
from multiprocessing import process import os time import sleep delay test = "first" def f(): global test print('hello') print("before: "+test) test = "second" if __name__ == '__main__': p = process(target=f, args=()) p.start() p.join() delay(1) print("after: "+test)
it's supposed change value of test
@ last value of test must second
, value doesn't change , remains first
. here output:
hello before: first after: first
the behavior you're seeing because p new process, not new thread. when spawn new process, copies initial process's state , starts executing in parallel. when spawn thread, shares memory initial thread.
since processes have memory isolation, won't create race-condition errors caused reading , writing shared memory. however, data child process parent, you'll need use form of inter-process communication pipe, , because fork memory, more expensive spawn. in computer science, have make tradeoff.
for more information, see:
- https://en.wikipedia.org/wiki/process_(computing)
- https://en.wikipedia.org/wiki/thread_(computing)
- https://en.wikipedia.org/wiki/inter-process_communication
based on you're trying accomplish, consider using threads instead.
Comments
Post a Comment