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()