Friday, November 7, 2008

RubyConf 2008 Day 2 - What Every Rubyist Should Know About Threads

Jim Weirich starts with an introduction of computer architecture, Moore's law, and how the market is looking to build more multicore systems than they are investing in faster CPUs.
Java and Ruby share similarities in their concurrent programming models, although I am not sure how much since JRE 1.5.

He is demonstrated ruby thread code which incremented a nuber:
@amount += 1

We expect that this operation is atomic but there are a few operations here:
@amount #read operation
+ 1 #object creation operation
@amount = (the result) #write operation

With ruby you can create a Mutex object to synchronize a block:
Mutex.new.synchronize do
@amount += amount
end

Jim also demonstrated deadlocks and the ruby script failed. Chain of threads where waiting for each other. Increases when you lock more than one resource at a time. Basically he is saying that multi-threading is difficult.

Its hard because we share mutable memory.

What can we do to write correct multi-threaded code?
Use Erlang => Only Constants, Pattern Matching, Recusion (tail) (Erland eats serial for breakfast!)
Use Clojure => pretty much a functional language. The language is designed to avoid deadlocks.

No comments: