From: Csaba Henk Date: 2005-02-27T19:44:59+09:00 Subject: Re: assignments and thread safety On 2005-02-27, Yohanes Santoso wrote: > Csaba Henk writes: > >> Is "$a ||= 1" thread safe? I'd guess so, as "||=" is one piece of > > It is not guaranteed to be thread-safe, although in current official > ruby vm it is 'atomic'. So that means it thread safe now, but it's not guaranteed to stay so? Is there a real chance/reason to make it non-atomic (either during the development of the current implementation, or in a new implementation Then how to do the following: I need a method which inserts an element into an array, named by an instance variable. The variable is possibly undefined. I want to make it thread-safe. The best I came up with is @a ||= [] @a << foo which then thread-safe by the current implementation, but not guaranteed to stay so... Note that I can't do "@a = []" in #initialize (as the code lies within a block passed to #define_method within an instance method definition of Module itself; so it's not just a simple static method definition for a certain class). If I had @mutex, @mutex.synchronize { @a ||= [] } @a << foo would do the job perfectly; but having @mutex is exactly the same problem as having @a ... Having @@mutex in the class would be fine as far as thread safety goes, but then all instances would use that same @@mutex on each call, absolutely unnecessarily after the first time... Maybe @@mutex.synchronize { @a ||= [] } unless @a @a << foo ? I don't have any better idea... >> Is it just an accident, or we can know somehow that this code is thread >> safe? Where do the limits of thread safety lie? > > Treat it as an accident and don't depend on this behaviour. You should > synchronise access to shared resources. Ah, thanks. I thought it's just this way. Regards, Csaba