0

I have a certain scenario (python 3.7+):

I have a python script, at some point during execution I begin a thread in daemon mode (using threading library) to send messages to an output device in an endless loop. Now, after this thread is started, periodically I'd like to change the message that is being sent. Also, at some point I'd like to "kill" the thread and stop the message send loop.

So the function the thread calls basically has a while True: loop that calls some message send function. Something like send_message(the_msg) where the_msg is a global variable. Then down the line if I want to adjust what is being sent, I just change the value of the_msg.

This works fine, I'm wondering if this approach based on the use case is OK. Also, I'm not too familiar with the asyncio and async/await features of 3.7+, is that library a candidate for this scenario? Is it worthwhile to switch from threading? In either case, how do you "kill" the thread or running process?

1
  • This sound like a very simple use case for both technologies. You will barely see a difference. Commented Jun 7, 2019 at 20:08

1 Answer 1

2

With regard to the two libraries I doubt you'd see a difference, though from a purely personal opinion I'd used threading for this use case.

As far as changing the message, threads use shared memory so accessing a global is suitable unless you have some other constraint?

To message that the thread should exit I'd use an event: Docs something like:

should_exit = threading.Event()

# Daemon Thread
while not should_exit.is_set():
    # Do stuff here

# Main Thread
should_exit.set() # this will exit the daemon thread
Sign up to request clarification or add additional context in comments.

Comments

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.