I was reading on this SO page about terminating a thread, and the accepted answer states that it's generally a bad idea, but they're situations when it's acceptable to do so.
That being said, suppose I have a while
and a boolean
to indicate if the loop should stop, is this terminating the thread (as explained in the link), and considered bad practice?
Example:
from threading import Thread
import queue
def print_number(number_queue_display):
loop = True
numbers = []
while loop:
number = number_queue_display.get()
if number is not None:
numbers.append(number)
else:
loop = False
print(numbers)
number_queue = queue.Queue()
printing_numbers = Thread(target=print_number, args=(number_queue,),)
printing_numbers.start()
number_queue.put(5)
number_queue.put(10)
number_queue.put(15)
number_queue.put(20)
number_queue.put(None)
printing_numbers.join()
Even when the while
loop ends, the thread continues and the numbers are printed, much like if this code was in the main thread.
I'm fully aware I don't need a thread to print numbers using a while
loop, but my bigger question is about the loop and the boolean