Mailing Lists: Apple Mailing Lists

Image of Mac OS face in stamp
 
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Thread safety question




On Feb 19, 2005, at 12:40 PM, Eric Gouriou wrote:
 Apologies for using examples not immediately relevant to Darwin,
but I don't want this idiom to become more prevalent. It is broken,
even if in not so obvious ways.

Doesn't the use of a compare-and-swap or similar pattern (such as test-and-set) solve this problem without a lock at all?


e.g

void * myVariable = 0;
volatile UInt32 sentinel = 0;

void* instance(void)
{
	if ( !OSCompareAndSwap( 0, -1, &sentinel))
	{
		/* initialize variables */		
		if ( ! myVariable )
			myVariable = allocateObject();
		/* etc */
		sentinel = 1;
	}
	else {
		while (sentinel != 1)
			/* yield, whatever that function is...pthread_yield()? */;
         }
	return myVariable;
}

You could use myVariable as the sentinel also but that introduces other dependencies, and besides you probably don't want to declare it volatile. If you were to do that, to avoid the inline-ordering problem you'd assign the output of allocateObject to a local variable, then to the global.

_______________________________________________
Do not post admin requests to the list. They will be ignored.
Darwin-dev mailing list      (email@hidden)
Help/Unsubscribe/Update your Subscription:
http://lists.apple.com/mailman/options/darwin-dev/email@hidden

This email sent to email@hidden
References: 
 >Thread safety question (From: Steve Gehrman <email@hidden>)
 >Re: Thread safety question (From: Rich Seibel <email@hidden>)
 >Re: Thread safety question (From: Eric Gouriou <email@hidden>)



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

Contact Apple | Terms of Use | Privacy Policy

Copyright © 2007 Apple Inc. All rights reserved.