0

I have a reading thread in my application that listens on stdin. It blocks until some input is available. When some arrive, it accepts the lines, checks if they are valid commands and put them in a queue.

def ReadCommands( queue ):
    for cmd in stdin:
        if cmd=="":
            break
        # Check if cmd is valid and add to queue

queue = Queue()
thread = Thread( target=ReadCommands, args=( queue, ) )
thread.start()

Now when the main program wants to exit, it first has to join on this reading thread. The problem is that the thread is in a loop I have no control over. Even stdin.close() does not work.

How can I break the for loop in the reading thread from the main?

Alternatively, how can I write the for loop (with a while?) to be able to add my own boolean variable that would break the loop? Beware that I don't want an active waiting loop!

5
  • threading.event may help you. You can check exit condition by is_set(). Oct 13, 2015 at 13:43
  • This is the link: docs.python.org/2/library/threading.html#event-objects Oct 13, 2015 at 13:45
  • I don't think this is related to your problem, but isn't args supposed to be a tuple? In which case you should do args=(queue,)
    – Kevin
    Oct 13, 2015 at 13:45
  • @Kevin Yes. Thanks. (I have two arguments in my actual code ...) Oct 13, 2015 at 13:46
  • @AnakinTung My problem is not to communicate to the reading thread that I want to stop. My problem is within the reading thread, how to add such a condition in the for cmd in stdin loop. Oct 13, 2015 at 13:48

1 Answer 1

1

If you have threads that you just want to shut down on exiting your program, starting them in daemon mode is often the best way to go. If all non-daemon threads exit, your application will end, taking all daemon threads with it.

Note that you should only do this for threads that do not have to perform cleanup; your example seems to be fine for this. Also, if you are performing a blocking C-level operation, a daemon thread may still block until it returns to the actual python scope. In that case, there is no python level option to break the block to begin with. Reading from broken sockets can be such an issue, for example.


If you need to explicitly kill a blocking thread before stopping your program, you will probably have to use the python's C-API. This can be implemented more cleanly but works in principle.

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.