Mailing Lists: Apple Mailing Lists
Image of Mac OS face in stamp
Re: Locks, cache coherency, @synchronized, double-checked locking, and lots and lots of doubts
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Locks, cache coherency, @synchronized, double-checked locking, and lots and lots of doubts



On Nov 29, 2006, at 12:46 AM, leenoori wrote:
So I accept that that point too, but I am struggling to understand it, and as a result I am doubting that even the slow (always-lock) pattern will work:

+ (void)onceOnlyInit
{
    static BOOL initialized = NO;
    @synchronized (thing)
    {
        if (!initialized)
        {
            PerformInitialization();
            initialized = YES;
        }
    }
}

This code is thread-safe. @synchronized uses pthread mutexes internally. pthread mutexes include any necessary barriers. Think of it this way:


+ (void)onceOnlyInit
{
    static BOOL initialized = NO;
    {
        pthread_mutex_lock(thing_lock);
        exception_safety_magic();
        if (!initialized)
        {
            PerformInitialization();
            initialized = YES;
        }
        pthread_mutex_unlock(thing_lock);
    }
}


Jens Ayton wrote:

It is my understanding that the compiler handles this by implicitly marking variables used both inside and outside a @synchronized() block as volatile. (In fact, I think it makes *all* variables in any function/method containing a @synchronized() block volatile, but don't quote me on this.)

To a first approximation, `volatile` never fixes thread-safety problems. @try and @synchronized use `volatile` to make sure variables have correct values if an exception is thrown.



-- Greg Parker email@hidden Runtime Wrangler

_______________________________________________
Do not post admin requests to the list. They will be ignored.
Objc-language mailing list      (email@hidden)
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden


References: 
 >Locks, cache coherency, @synchronized, double-checked locking, and lots and lots of doubts (From: leenoori <email@hidden>)



Visit the Apple Store online or at retail locations.
1-800-MY-APPLE

Contact Apple | Terms of Use | Privacy Policy

Copyright © 2011 Apple Inc. All rights reserved.