0

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()
Anil Nivargi
  • 1,473
  • 3
  • 27
  • 34
john
  • 1
  • Start by looking at the multiprocessing communication tools in the standard library: [Exchanging objects between processes](https://docs.python.org/3/library/multiprocessing.html#exchanging-objects-between-processes). Then try that out and come back if you have a more specific question – blarg Apr 08 '22 at 22:39

1 Answers1

0

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()
Booboo
  • 38,656
  • 3
  • 37
  • 60