ruby - Why does the puts method behave strangely when used in a thread? -
ruby - Why does the puts method behave strangely when used in a thread? -
solution: in .irbc file, put: irb.conf[:use_readline] = false
i running ruby code:
thread.new loop = @queue.pop puts "1" puts "2" end end
when run in irb, , queue pops, print "1", doesn't print "2" right away. have press come in couple of times before spits out "2". why that?
here's irb log:
>> thread.new ?> loop ?> = @queue.pop >> puts "1" >> puts "2" >> end >> end => #<thread:0x10ae6d1a0 sleep> >> @queue << "something random" 1=> #<queue:0x10aed6420> >> ?> ?> ?> 2?>
here's get:
>> require "thread" => true >> ?> @queue = queue.new => #<queue:0x101bc9a60> >> ?> thread.new ?> loop ?> = @queue.pop >> puts "1 printed @ #{time.now.to_f}" >> puts "2 printed @ #{time.now.to_f}" >> end >> end => #<thread:0x101bb8058 sleep> >> ?> @queue << 42 1 printed @ 1328144684.33667=> #<queue:0x101bc9a60> >> ?> ?> ?> 2 printed @ 1328144686.4642?>
i experimented , found out happening. might know, 2 ruby threads cannot run @ same time; switch , forth quickly.* normally, if phone call gets
, calling thread wait input, , other threads go on (because gets
releases gil ). however, in irb, (at to the lowest degree on mac os x) other threads not go on execute while waiting input. example:
>> = 0 => 0 >> thread.new { loop { += 1 } } => #<thread:0x1094d6d68 run> >> => 234866 >> => 401271
if thread executing, i
in millions. (tested outside irb.) plus, ruby using < 1% cpu.
in example, each time press enter, thread gets split sec execute--enough time write out number or newline. ruby switches irb's thread, writes prompt , waits on input.
* jruby, ironruby, , rubinius 2.0, multiple threads can run @ same time.
edit: tested on windows, , threads maintain running there. if want threads maintain running on mac, save as, say, sirb.rb (simple irb) , utilize instead of irb:
$stdout.sync = true while true print "> " p(eval gets) end
note that, unlike irb, doesn't back upwards statement spanning multiple lines, nor back upwards moving caret edit or pressing history (on mac os x). example:
> in 1..10; print ** 2, " "; end; puts 1 4 9 16 25 36 49 64 81 100 nil
ruby multithreading
Comments
Post a Comment