I would like share a variable with the main thread of a process spawned from the main of program and thread spawned from the same process.
Variable I want to share is not a simple object like array or int. This a socket zmq.socket object for my case but it could be any python object. This shared variable should only be accessible in the spawned process so declaring as a global variable is not acceptable.
Thanks in advance.
def process_function():
# print init
pid = os.getpid()
print("PROCESS STARTS", pid)
var = #this want to use in thread
# create a thread
thread = threading.Thread(target=thread_function)
thread.start()
... # stuff
thread.join()
def thread_function():
# print start prompt
print("THREAD STARTS")
#do stuff with var
# In main if __name__ == '__main__': p = multiprocessing.Process(target=process_function, args=()) p.start() #do stuff p.join()
EDIT 1
I have discovered a way using global keyword.
def process_function():
global var # this is new
#this var is only global within process, if you create
#many processes each will have its own var
# print init
pid = os.getpid()
print("PROCESS STARTS", pid)
var = #this want to use in thread
# create a thread
thread = threading.Thread(target=thread_function)
thread.start()
... # stuff
thread.join()
def thread_function():
global var #this is new as well
# print start prompt
print("THREAD STARTS")
#do stuff with var
# In main if __name__ == '__main__': p = multiprocessing.Process(target=process_function, args=()) p.start() #do stuff p.join()