"J?rg W Mittag" <JoergWMittag+Usenet / GoogleMail.Com> wrote in message 
news:a4cg2zmfjkh9$.dlg / jwmittag.my-fqdn.de...
> 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?
>
> This is a *very* interesting question! And it is a question that can
> ultimately *only* be answered by a formal Ruby Specification or more
> specifically a formal Ruby Memory Model.
>
> Until we have such a specification, the C source code of MRI or YARV
> is considered to be the "specfication". However, there is a problem:
> that source code can actually be interpreted several different ways.
>
> If you look at the implementations of Hash, Array and friends, you
> will see that they are not thread-safe. Ergo: the specification says
> that the user is responsible for locking Arrays and Hashes.
>
> If, however, you look at the implementation of threads, you will see
> that both MRI and YARV are actually incapable of running more than one
> thread at a time -- even on a 1000-core machine MRI and YARV will only
> ever use one core. So, since two threads can never access an Array at
> the same time, there is no need for locking. Ergo: the specification
> says that the user is *not* responsible for locking Arrays and Hashes.

    I don't think this is relevant.  Concurrency isn't about how many 
processors you use.  Multitasking systems existed long before SMP hardware 
existed.  Concurrency is about doing tasks concurrently.  If you have one 
method running and it may be preempted by another method then they are 
running concurrently.  If the two methods share data then they may corrupt 
that data for each other.  This is true regardless of how these 
concurrencies, or threads, are implemented.  It doesn't matter if they're 
hardware supported system threads or if they're Ruby green threads...


> So, in short: when in doubt, lock.

    This is the popular wisdom so this is what I will do.  Better safe than 
not thread-safe!