I wrote this code about ruby thread to open 50 threads and every thread wait for 2s.
#!/home/sun/.rvm/rubies/ruby-1.9.3-p448/bin/ruby
ts = []
50.times do |p|
ts << Thread.new do
sum = 0
5.times do |i|
sleep(2)
end
puts "turn "+p.to_s+" finished"
end
end
ts.each {|x| x.join}
and to compare with ruby eventmachine, i can't use sleep in EM.do , because it will block the reactor of eventmachine.
so I tried to write code below:
#!/home/sun/.rvm/rubies/ruby-1.9.3-p448/bin/ruby
require 'eventmachine'
ts = []
EM.run do
q = 0
def dfs(tm)
return 0 if tm == 0
EM.add_timer(2) do
dfs(tm-1)
end
end
50.times do |p|
op = proc do
dfs(5)
end
callback = proc do
puts "turn "+p.to_s+" finished"
q += 1
if q == 50
EM.stop
end
end
EM.defer(op,callback)
end
end
But it runs over in just 1s. I don't know how to code to let it wait some seconds in every eventmachine loop.
Can anybody give some help? Thanks!