Double Checked Locking

Jonathan M Davis jmdavisProg at gmx.com
Sat Dec 17 15:03:15 PST 2011


On Saturday, December 17, 2011 09:50:26 Andrei Alexandrescu wrote:
> On 12/17/11 1:56 AM, Andrew Wiley wrote:
> > On Sat, Dec 17, 2011 at 1:47 AM, Andrew Wiley<wiley.andrew.j at gmail.com>  
wrote:
> >> I was looking through Jonathan Davis's pull request to remove static
> >> constructors from std.datetime, and I realized that I don't know
> >> whether Double Checked Locking is legal under D's memory model, and
> >> what the requirements for it to work would be.
> >> (if you're not familiar with the term, check out
> >> http://en.wikipedia.org/wiki/Double-checked_locking - it's a useful
> >> but problematic programming pattern that can cause subtle concurrency
> >> bugs)
> >> It seems like it should be legal as long as the variable tested and
> >> initialized is flagged as shared so that the compiler enforces proper
> >> fences, but is this actually true?
> > 
> > This entry in the FAQ makes me suspicious:
> > ```
> > What does shared have to do with memory barriers?
> > 
> > Reading/writing shared data emits memory barriers to ensure sequential
> > consistency (not implemented).
> > ```
> > 
> > So DCL should be alright with data flagged as shared, but it's not
> > implemented in the compiler?
> 
> That is correct.

Well, you learn something new every day I guess. I'd never even heard of 
double-checked locking before this. I came up with it on my own in an attempt 
to reduce how much the mutex was used. Is the problem with it that the write 
isn't actually atomic? Wikipedia makes it sound like the problem might be that 
the object might be partially initialized but not fully initialized, which I 
wouldn't have thought possible, since I would have thought that the object 
would be fully initialized and _then_ the reference would be assigned to it. 
And it's my understanding that a pointer assignment like that would be atomic. 
Or is there more going on than that, making it so that the assignment itself 
really isn't atomic?

- Jonathan M Davis


More information about the Digitalmars-d mailing list