eventmachine:如何实现并发?

时间:2013-02-04 08:04:38

标签: ruby eventmachine

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

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

2 个答案:

答案 0 :(得分:1)

我认为你将并发与多线程混淆了。事件机器是单线程的...查看示例如何模拟并发:
https://github.com/eventmachine/eventmachine/wiki/Code-Snippets

答案 1 :(得分:0)

您可能希望使用EventMachine#map方法:

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

我没有测试代码,因为我没有这里的env,但它应该给你一个提示。希望它有所帮助。