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: 2024-11-21

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)

Thread.new do
  Thread.current.abort_on_exception = true
  $stdin.getc
  exit
end

loop do
  # main code
end

Resources