SOLUTION: In .irbc file, put: IRB.conf[:USE_READLINE] = false
I am running some ruby code:
Thread.new do
loop do
a = @queue.pop
puts "1"
puts "2"
end
end
When i run this in irb, and queue pops, it print “1”, but doesn’t print “2” right away. I have to press enter couple of times before it spits out “2”. Why is that?
Here’s my irb log:
>> Thread.new do
?> loop do
?> a = @queue.pop
>> puts "1"
>> puts "2"
>> end
>> end
=> #<Thread:0x10ae6d1a0 sleep>
>> @queue << "something random"
1=> #<Queue:0x10aed6420>
>>
?>
?>
?>
2?>
Here’s what I get:
>> require "thread"
=> true
>>
?> @queue = Queue.new
=> #<Queue:0x101bc9a60>
>>
?> Thread.new do
?> loop do
?> a = @queue.pop
>> puts "1 was printed at #{Time.now.to_f}"
>> puts "2 was printed at #{Time.now.to_f}"
>> end
>> end
=> #<Thread:0x101bb8058 sleep>
>>
?> @queue << 42
1 was printed at 1328144684.33667=> #<Queue:0x101bc9a60>
>>
?>
?>
?>
2 was printed at 1328144686.4642?>
I experimented some and found out what is happening. As you might know, two Ruby threads cannot run at the same time; they just switch back and forth quickly.* Normally, if you call
gets, the calling thread will wait for input, and other threads will continue (becausegetsreleases the GIL ). However, in irb, (at least on Mac OS X) other threads do not continue to execute while it is waiting for input. Example:If the thread were executing,
iwould be in the millions. (Tested outside irb.) Plus, ruby was using < 1% CPU.In your example, each time you press enter, the thread gets a split second to execute–enough time to write out a number or a newline. Then ruby switches back to irb’s thread, which writes the prompt and waits on input.
* With JRuby, IronRuby, and Rubinius 2.0, multiple threads can run at the same time.
Edit: I tested on Windows, and threads keep running there. If you want threads to keep running on Mac, you could save this as, say, sirb.rb (simple irb) and use it instead of irb:
Note that, unlike irb, it doesn’t support a statement spanning multiple lines, nor does it support moving the caret to edit or pressing Up for history (on Mac OS X). Example: