views:

131

answers:

5

I have a multithreaded application (C++) where I need to increment/change a series of values. If I use a series of Interlocked operations, are they considered to be a single atomic operation ? Like in this example:

InterlockedIncrement(&value1);
InterlockedIncrement(&value2);
InterlockedExchange(&oldValue, newValue);

Or it would be better to us a lock to perform the synchronization ? Like this:

EnterCriticalSection(&cs);
value1++;
value2++;
oldValue = newValue;
LeaveCriticalSection(&cs);

I think a lock is required, but I'm not sure... it's very important that all the values to be either in the old state, or in the new one, together.

+13  A: 

InterlockedIncrement itself is an atomic operation but series of InterLockedIncrement are not atomic together. If your requirement is to get the atomicity for series of operation then you can use critical section.

aJ
Naveen
+1  A: 

You should use critical section to ensure atomicity.

msvcyc
+3  A: 

If the values must be fully executed to leave a consistent state, you will need to use the critical section. For example, if your values were actually something like

   President = Barack Obama;
   VP = Joe Biden;

and you weren't using a critical section, you could be in a situation where Barack Obama was put in as President and Dick Cheney was VP if you had some kind of interruption or context switch between the execution of those statements. This state is inconsistent I think we would all agree :)

However, if you are doing something like

   Debit $5 from account;
   Credit $2 to account;

and the result of each operation left a complete state, the interlock will be fine.

Doug T.
+1 for the nice example..
Naveen
A: 

You have to define what the "state" is. It looks like you want all three variables to change atomically - in this case three individual atomics are not enough. But if you can group all the state into an object of some sort, you should be able to use "swap a pointer" technique for updating state.

Nikolai N Fetissov
+1  A: 

You're right, since all the values to be either in the old state, or in the new one, together; you should use the Critical Section

Peter Mourfield