On Sat, 25 Aug 2007, Aaron S. wrote:
I’m looking for some information about handling thread safety with Ruby.
I’ve got an application server I wrote that I need to make sure it’s
thread safe. This application server is used over http requests so it’s
possible multiple people hit it at once. I have some questions that will
help me determine…
In general, it’s the same as any other type of threaded programming.
Share as little as possible, and control access to shared resources so
that two threads aren’t changing state in it at the same time and
into eachother. Look at the Mutex class and the Queue class as starting
points for tools to help you do this.
- Does using mongrel / lighttpd / webrick, ensure thread saftey? (my
application relies on these)
lighttpd is an external web server, so it’s irrelevant.
Both mongrel and webrick are threaded Ruby web server platforms. They,
however, don’t do anything to ensure that your code which you run inside
of them is threadsafe.
- What kinds of things in the Ruby language should I NOT do that will
cause thread headaches… (maybe static variables)?
The only things to really keep in mind is that Ruby threads are green
threads – they are all done inside of the Ruby interpreter. So, they
share a single process. Thus, the use of threads will rarely increase
throughput of your program, unless there is some external latency that
be captured, and that external latency does not occur inside of a Ruby
This is because while the flow of execution is inside of an extension,
is out of Ruby’s control, and no thread task switching will take place.
Also, be aware that Ruby uses a select() loop to manage its threads of
execution, and it has an fd_setsize limit of 1024 handles, so there is a
sharp upper boundary on the number of threads you can have in a Ruby
- What techniques can I use to go about testing thread saftey?
Look for areas in your code where you share resources between your
threads. Do you take precautions to keep multiple threads from stepping
on eachother when using those resources?
Write test code that creates multiple threads, and tries to stress those