Re: Thread safety question
Re: Thread safety question
- Subject: Re: Thread safety question
- From: "Matthew T. Russotto" <email@hidden>
- Date: Sat, 19 Feb 2005 17:28:38 -0500
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:
This email sent to email@hidden