Issue
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?
Solution
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
Answered By - pypypy
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.