1

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

  • That link was about terminating a thread without using any sort of flag and trying to get around python's restriction that only the main thread can be signaled. In C for instance, you could signal the thread, which would cause the next blocking operation to return with an error, which the program could catch and do its cleanup. – tdelaney May 07 '18 at 04:50

1 Answers1

1

This is a very good way to manage a thread. You have a work queue and you've defined an end condition when the threaded function gets a None value.

That's very different from the linked question where the problem is terminating a thread without a semaphore, flag, etc... Essentially, trying to terminate a thread that hasn't setup a cooperative way of doing so.

Your None is a flag telling the function to return. And when a thread function returns, its thread is terminate.

tdelaney
  • 73,364
  • 6
  • 83
  • 116
  • So the `boolean` that tells the `while` to end isn't killing the thread as stated in the other link, correct? In other words, the `boolean` to stop the `while` loop is safe, and doesn't violate what the linked post warns against? If it were, the code after the loop won't execute, but in this case it does, meaning the thread is naturally able to stop. –  May 07 '18 at 13:39
  • The accepted answer was warning you against the solution he proposed, not the use of flags. He injected an exception into the thread and that can be risky - the thread gets an exception it didn't expect and may not exit gracefully. – tdelaney May 07 '18 at 15:03