Question

I read somewhere that ruby threads/fibre block the IO even with 1.9. Is this true and what does it truly mean? If I do some net/http stuff on multiple threads, is only 1 thread running at a given time for that request?

thanks

Was it helpful?

Solution

Assuming you are using CRuby, only one thread will be running at a time. However, the requests will be made in parallel, because each thread will be blocked on its IO while its IO is not finished. So if you do something like this:

require 'open-uri'
threads = 10.times.map do
  Thread.new do
    open('http://example.com').read.length
  end
end

threads.map &:join
puts threads.map &:value

it will be much faster than doing it sequentially.

Also, you can check to see if a thread is finished w/o blocking on it's completion.

For example:

require 'open-uri'
thread = Thread.new do
  sleep 10
  open('http://example.com').read.length
end
puts 'still running' until thread.join(5)
puts thread.value

With CRuby, the threads cannot run at the same time, but they are still useful. Some of the other implementations, like JRuby, have real threads and can run multiple threads in parallel.

Some good references:

OTHER TIPS

All threads run simultaneously but IO will be blocked until they all finish.

In other words, threading doesn't give you the ability to "background" a process. The interpreter will wait for all of the threads to complete before sending further messages.

This is good if you think about it because you don't have to wonder about whether they are complete if your next process uses data that the thread is modifying/working with.

If you want to background processes checkout delayed_job

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top