这是我的代码,我使用 sleep 来模拟长时间运行的请求
require 'eventmachine'
def test (i)
puts "#{i} start to sleep..."
sleep i
puts "#{i} end..."
end
EventMachine.run do
(1..3).each do |i|
test i
end
Signal.trap("INT") do
connection.close do
EM.stop { exit }
end
end
end
它给了我:
1 start to sleep...
#### after 1 second
1 end...
2 start to sleep...
#### after 2 seconds
2 end...
3 start to sleep...
#### after 3 seconds
3 end...
我想得到:
#### immediately
1 start to sleep...
2 start to sleep...
3 start to sleep...
#### after 1 second
1 end...
#### after 1 second
2 end...
#### after 1 second
3 end...
我的代码有什么问题?如何并发?或者我该怎么做?