简体   繁体   中英

python - threading and infinite loops

inside the main python script, at a point variable VAR is set and thread THR is executed with variable VAR as starting value.
within THR there's an infinite loop, which prints VAR every 500 ms .
meanwhile the main script crunches some more data and VAR is updated.

how do I reflect the change to THR , so that the printed output will change as well, without killing it and spawning a new one?

this is a very rough simplification of the code I have of course, but I'd rather read and focus on an example skeleton rather than on my particular case.

EDIT: as per request here's the code I have in mind

import threading

VAR = 0

def function():
    while True:
        global VAR
        while VAR == VAR:
            print VAR
            time.sleep(0.5)

THR = threading.Thread(target=function)
THR.start()
time.sleep(1)
function().VAR = 4 # this doesn't affect the output, only adds a seemingly random whitespace before it
time.sleep(2)
THR.VAR = 5 # nothing changes

You should use a list with your variable inside.

If you pass the list to the function, you will be able to modify the value of the first position of the list (outside the function) and at the same time you'll see how the thread prints the correct value.

Pseudocode:

(THREAD)
    while True:
        print list[0]

(MAIN)
    start_thread(list)
    #modify value
    list[0] = X

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM