What is the threading class if I just want to test and set a flag in a threadsafe manner?

I just want to do a simple, though thread-safe, boolean test (and set) so:

if(myBoolean==false)   //should not lock/wait!
{ 
     myBoolean=true;
     .....
}
else
{
     ....
}

I considered the following (although possibly incorrectly, so please correct me where I misunderstood)

  • using the Lock { if(myBoolean)... } construct seems like a overkill way to do it. And, it also locks the thread while it waits for the lock to become free. I don't want this.
  • The AutoResetEvent class does have a concept of a boolean state, but it is used to signal another thread which is waiting. So not relevant in my case
  • Semaphore class has a notion of a reference count (probably to throttle the amount of access to a resource?). So probably not what I'm after.
  • Mutex class. As far as I understood, this is the same principal as the Lock primitive

Anyone have an idea what is the class/construct to do this in an efficient manner?

Answers


Consider Interlocked.CompareExchange.


Need Your Help

streaming wav files

c++ stream wav

I have a server that sends data via a socket, the data is a wav 'file'. I can easily write the data to disk and then play it in WMP, but I have no idea how I can play it as I read it from the socke...

Some HTML tags in page don't work on adding div

css google-chrome html hyperlink

The problem that I am currently facing is that I the links that are attached to the HOME and ABOUT ME options (see in header) are not available on adding the 'data' div. However, the links for DOWN...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.