Reputation: 8582
Here is my code, I use sleep to simulate a long running request
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
It gives me :
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...
I suppose to get:
#### 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...
What is wrong with my code?How to be concurrency? Or how can I do it?
Upvotes: 0
Views: 414
Reputation: 120990
You likely want to use EventMachine#map method:
EM::Iterator.new(1..3).map(proc{ |num,iter|
iter.return(test(num))
}, proc{ |results|
p results
})
I didn’t test the code since I have no env here, but it should give you a tip. Hope it helps.
Upvotes: 0
Reputation: 1511
I think you mixed up concurrency with multithreading. Event machine is single threaded... Look at the examples how to simulate concurrency:
https://github.com/eventmachine/eventmachine/wiki/Code-Snippets
Upvotes: 1