Thread safety

J

Jeff Turc

With the discussion surrounding merb/rails and thread safety, I've been
somewhat concerned with making my own tiny home-rolled web apps that I
write thread safe, if only to become more knowledgeable on the subject.

I know it's probably hard to generalize, but does anybody have any
simple rules to follow (or resources to share) for writing thread safe
code?

Thanks!
 
S

s.ross

With the discussion surrounding merb/rails and thread safety, I've
been
somewhat concerned with making my own tiny home-rolled web apps that I
write thread safe, if only to become more knowledgeable on the
subject.

I know it's probably hard to generalize, but does anybody have any
simple rules to follow (or resources to share) for writing thread safe
code?

Thanks!


Anyone else jump right in here. These are mine:

Rule #1: Don't use global variables.
Rule #2: If you do, when you change them, wrap them in a blocking
mechanism such as a mutex or critical section so two threads can't try
at once.
Rule #3: If you are changing the state of an object that is not thread-
local, wrap the change in a mutex (etc.)

So, for example:

require 'thread'
my_object_sync = Mutex.new

Thread.new do
# just lock on this object
my_object_sync.synchronize do
# Update that is not atomic
end
end

Rule #4: Don't be too sure that any operation in Ruby is atomic.
 
R

Robert Klemme

Rule #3: If you are changing the state of an object that is not thread-
local, wrap the change in a mutex (etc.)

Corollary: use thread confinement, i.e. design your app in a way that
most objects are used in a single thread at a time only. Restrict need
for synchronization to the minimum needed.
Rule #4: Don't be too sure that any operation in Ruby is atomic.

Somehow this reminds me of "Blondie" and "Atomic". :) Those were the
days...

Cheers

robert
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,733
Messages
2,569,439
Members
44,829
Latest member
PIXThurman

Latest Threads

Top