1

how do I update a variable inside a running thread, which is an infinite loop based on such variable?
a simplified version of what I tried is what follows, to no results of course, and I can't find any pointer.

import some_module as mod
import threading

class thr (threading.Thread):
    NUM = 5  # set a default value to start the script
    def run (self):
        mod.NUM = NUM
        mod.main_loop()

try:
    thr().start()
    time.sleep(1)
    thr().NUM = 2
    time.sleep(1)
    thr().NUM = 6
    time.sleep(1)
    thr().NUM = 8

2 Answers 2

1

The problem is that you're creating a new thread each time you "call" (i.e. instantiate) thr. Change your code to

t = thr()
t.start()
time.sleep(1)
t.NUM = 2
time.sleep(1)
t.NUM = 6
time.sleep(1)
t.NUM = 8
time.sleep(1)
Sign up to request clarification or add additional context in comments.

7 Comments

unfortunately it still doesn't update the variable inside the infinite loop
It updates the NUM variable in the thread object instance... to update mod.NUM just do that with mod.NUM = 2 ... etc.
that far I've gotten already, my problem here is that the updated variable is not being fed to the infinite loop...
@nxet: what loop? you're asking what is the problem in code not shown? My wild guess is that the statement at line 42 in some_module.py contains a mistake... but it's a VERY wild guess :-D
man I was this close to open up some_module.py and see for any error there :/ this is how lost I am here. basically the thread I'm launching has an infinite loop within, and the variable I want to update is what the loop parses to execute. I thought it was irrelevant, but at this point it might be worth noting that some_module.py actually is a multiplexing script. basically I say '5 7' to the module, and it runs infinitely multiplexing said values between two led bars (extremely roughly explained). I need to update the value and see the change reflected with the leds
|
0

Maybe try use queue for change NUM variable.

https://docs.python.org/2/library/queue.html

Check examples here :

https://pymotw.com/2/Queue/

Generally speakinig the queue allows You send data between threads. Use get() for getting data from queue and put() for put data to queue.

3 Comments

I'm afraid that's a bit too generic for my limited knowledge of the language, and reading the link provided didn't help much unfortunately. can you please elaborate a bit more on this? thanks a lot
the second link was way more helpful. but am I wrong to assume I'm forced to kill and spawn a new thread everytime?
@nxet I don`t uderstand :)What mean - "I'm forced to kill and spawn a new thread everytime?"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.