From: Robert Klemme Date: 2008-12-24T00:16:23+09:00 Subject: Re: Are all Ruby built-in objects thread safe? On 23.12.2008 10:24, Just Another Victim of the Ambient Morality wrote: > Are all built-in objects thread safe? For example, if I have an array > and one thread is constant appending to it while another thread is shifting > elements off of it and there's no synchronization going on, can the array > object ever get corrupted? What about a similar scenario for hashes? These > are surely complicated objects with internal state that must be maintained. > Are they implemented to be thread safe? The answer will sound a bit odd: they are not built to be thread safe but it may well be that they are. In fact, it may well depend whether they are thread safe in practical terms depending on the Ruby version you are using. Since the classic interpreter uses green threads, i.e. no preemption is happening, it may be that some or all operations are atomic and thus thread safe. The bottom line is: you should not rely on this and assume they are not thread safe! In your example, you should be using class Queue which is thread safe and can be imported by requiring "thread" $ irb -r thread irb(main):001:0> q = Queue.new => # irb(main):002:0> t = Thread.new(q) {|qq| while (o = qq.deq) != qq; p o; end} => # irb(main):003:0> 5.times {|i| q.enq i}; q.enq q; t.join 0 1 2 3 4 => # Then there are also classes Mutex and Monitor plus module MonitorMixin. The difference is reentrance: irb(main):009:0> require 'monitor' => true irb(main):010:0> m=Mutex.new => # irb(main):011:0> m.synchronize { m.synchronize { 1 } } ThreadError: stopping only thread note: use sleep to stop forever from (irb):11:in `synchronize' from (irb):11 from (irb):11:in `synchronize' from (irb):11 from (null):0 irb(main):012:0> m=Monitor.new => # irb(main):013:0> m.synchronize { m.synchronize { 1 } } => 1 irb(main):014:0> Kind regards robert