Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save kurotoshiro/332949 to your computer and use it in GitHub Desktop.
Save kurotoshiro/332949 to your computer and use it in GitHub Desktop.
Ruby's threads and non-blocking gets for Windows
if RUBY_PLATFORM =~ /win32/
require 'Win32API'
$win32_console_kbhit = Win32API.new("msvcrt", "_kbhit", [], 'I')
def console_input_ready?
$win32_console_kbhit.call != 0
end
def nonblocking_stdin_gets
sleep(0.1) until console_input_ready?
$stdin.gets # don't bother to use getc, it also blocks until user hits <return>
end
else
def nonblocking_stdin_gets
$stdin.gets # it just works, on unix
end
end
threads = []
threads << Thread.new {
while true
input=nonblocking_stdin_gets
exit if input.strip=="Q"
end
}
threads << Thread.new {
100.times do |t|
puts "THREAD : #{t}"
sleep(1)
end
}
threads.each {|thr| thr.join}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment