'Acessing threading variable from multiprocessing function
I am new to python so i have the bellow code, and i want to acess xtime variable from time_print() function witch is multiprocessing. any idea ? seems only can access the initialized value, so i want when new xtime value is setted from auto_time function to be available in time_print function. any ideas ?
import time
import multiprocessing
import _thread
xtime = None
def auto_time():
global xtime
while 1:
xtime = int(time.time())
time.sleep(10)
_thread.start_new_thread(auto_time, ())
def time_print():
while 1:
print(xtime)
def printTime():
p = multiprocessing.Process(target=time_print, args=())
p.start()
printTime()
Solution 1:[1]
The most straightforward way is to use an integer value that resides in shared memory that can be accessed by all processes. See `multiprocessing.Value'.
A few other points:
Rather than import _thread, it is more standard to use the threading module as in the code below. I have also made the started thread and process a daemon thread and process respectively so that they will automatically terminate when the main process terminates, which I will let run for 10 seconds for demo purposes (I have correspondingly changed the sleep time in auto_time to just 1 second).
Also, the more "Pythonic" way of coding an infinite loop is with while True: instead of while 1:.
Finally, you have a race condition: It is possible for your process time_print to be attempting to print the time before the thread has had a change to initialize it (assuming that xtime was sharable). The code below ensures that xtime is initialized with a valid time value before time_print attempts to print it out.
import time
import multiprocessing
import threading
def auto_time(xtime):
while True: # This is the idiom to use
xtime.value = int(time.time())
time.sleep(1) # Changed to 1 second interval
def time_print(xtime):
while True:
print(xtime.value)
def printTime():
# Initialize value with a time to avoid a race condition:
xtime = multiprocessing.Value('i', int(time.time()), lock=False) # integer value
# Make these daemon threads and processes so that they
# terminate when the main process terminates:
threading.Thread(target=auto_time, args=(xtime,), daemon=True).start()
multiprocessing.Process(target=time_print, args=(xtime,), daemon=True).start()
# Run for 10 seconds and then quit
time.sleep(10)
# required by Windows:
if __name__ == '__main__':
printTime()
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Booboo |
