Search code examples
cmultithreadingvisual-studio-2010winapiinterlocked

thread-safe variables comaprison C VS2010


threaded programming

I want to write simple multi-thread app.

where each thread when it open I increment (using InterlockedIncrement) member by one , and decrements it (using InterlockedDecrement) when thread finishes

I know about Mutex/Semaphore/event

but I would more clean /simple way to implement comparison similar to the Interlocked function .

What I need next is implement comparison function [if(member == x)]

simple example:

Thread 1 function:

{
//do somthing 
InterlockedDecrement(member);
}

Thread 2 function:

{
//do something else
InterlockedDecrement(member);
}

main thread function :

{
  while(member)//<--how can it be done in thread safe fashion
  {
    //do yet another something
  }
}

Solution

  • Use InterlockedAdd and add 0. This will lock the member and return the value without changing it:

    while (InterlockedAdd(&member, 0) == someValue) 
    {
        //do yet another something
    }