Create a separate thread to handle user input

This is part of the Semicolon&Sons Code Diary - consisting of lessons learned on the job. You're in the architecture category.

Last Updated: 2021-05-15

Say you have a command line program and you want it to exit whenever you press enter (or some other key: it doesn't matter - basically you want any way of leaving the program without sending a signal)

How would you program that?

The trick is to create an extra thread scans stdin for input keys and then reacts to them (e.g. by exiting) do
  Thread.current.abort_on_exception = true

loop do
  # main code