Pergunta

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!

Foi útil?

Solução

The efficiency will be dependant on your workload. If you're doing a lot of IO work then EM has a good chance of winning as you won't incur the cost of context switches. There is a lot of time spent idle when doing IO.

On the other hand, if you're doing compute intensive work, then it, again, depends. EM has a thread pool with 20 threads, if you have more then 20 parallel computations then spawning the right number of Ruby threads will be better.

EM threads are just Ruby threads. They're kept in a thread pool so you save a bit of overhead starting/stopping the thread as it executes. EM also handles passing work out to the threads when you've asked for more then 20 items of work.

If you want to compare them, just create an EM program and a threaded program that are the same that model your workload. Then time how long they take to finish.

Outras dicas

Eventmachine is single-threaded. You can't compare them. If you want to test real situation then you can try DB 'sleep'. e.g. mongo http://docs.mongodb.org/manual/reference/command/sleep/ . But use EM library for request. e.g. https://github.com/bcg/em-mongo

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top