• Open Menu Close Menu
  • Apple
  • Shopping Bag
  • Apple
  • Mac
  • iPad
  • iPhone
  • Watch
  • TV
  • Music
  • Support
  • Search apple.com
  • Shopping Bag

Lists

Open Menu Close Menu
  • Terms and Conditions
  • Lists hosted on this site
  • Email the Postmaster
  • Tips for posting to public mailing lists
Re: Thread safety question
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

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


  • Follow-Ups:
    • Re: Thread safety question
      • From: Eric Gouriou <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>)

  • Prev by Date: Re: Thread safety question
  • Next by Date: Re: Thread safety question
  • Previous by thread: Re: Thread safety question
  • Next by thread: Re: Thread safety question
  • Index(es):
    • Date
    • Thread