Fabio
Fabio

Reputation: 1505

Can I use interlocked operations to update multiple values to avoid locking a critical section/mutex?

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.

Upvotes: 3

Views: 654

Answers (5)

Peter Mourfield
Peter Mourfield

Reputation: 1885

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

Upvotes: 1

Nikolai Fetissov
Nikolai Fetissov

Reputation: 84159

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.

Upvotes: 1

Doug T.
Doug T.

Reputation: 65599

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.

Upvotes: 4

msvcyc
msvcyc

Reputation: 2593

You should use critical section to ensure atomicity.

Upvotes: 1

aJ.
aJ.

Reputation: 35450

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.

Upvotes: 14

Related Questions