Created
March 15, 2010 15:29
-
-
Save kurotoshiro/332949 to your computer and use it in GitHub Desktop.
Ruby's threads and non-blocking gets for Windows
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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