0

这是我的代码,我使用 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...

我的代码有什么问题?如何并发?或者我该怎么做?

4

2 回答 2

1

我认为您将并发与多线程混为一谈。事件机是单线程的……看例子如何模拟并发:
https ://github.com/eventmachine/eventmachine/wiki/Code-Snippets

于 2013-02-04T08:36:19.540 回答
0

您可能想使用EventMachine#map方法:

EM::Iterator.new(1..3).map(proc{ |num,iter|
  iter.return(test(num))
}, proc{ |results|
  p results
})

我没有测试代码,因为我这里没有环境,但它应该给你一个提示。希望能帮助到你。

于 2013-02-04T09:11:41.077 回答