Science_Fiction
Science_Fiction

Reputation: 3433

InterlockedExchange (or similar atomic operation) within a Critical Section?

I have seen some repeated code (methods to be precise) where they are entering the critical section and then using InterlockedExchange...Does this make sense since I thought that this operation was infact atomic and would not require such synchronization?

{ 
  EnterCricSectionLock lock (somelock);
  InterlockedExchange(&somelong, static_cast<long>(newlongVal));
}

That is basically what there is...

Upvotes: 1

Views: 991

Answers (2)

Necrolis
Necrolis

Reputation: 26171

A single atomic operation won't need a CS, but it can act as a fence to make anything altered while the lock is held globally visible (IIRC, explicit fences are for SSE2+, but interlocked ops don't need SSE at all), however then it would need to be after any global stores.

Where this might make sense is that the CS is used to lock access to something else, and thus global being exchanged on is not part of the lock.

Upvotes: 1

rasmus
rasmus

Reputation: 3216

A normal exchange is generally not atomic. It is however ok to do it while owning a mutex, if all other uses is protected by the same mutex. It is also ok to use an atomic exchange, if all other uses are atomic. The only logical reason I can think of to do an atomic exchange while owning the mutex, is that not all uses of this value is mutex protected.

Upvotes: 1

Related Questions