Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between interlocked variable access AND critical sections interlocked increment

can someone help explain the different between interlocked variable access AND critical sections interlocked increment in c++? thanks, much appreciated, in advance.

like image 408
Beef Avatar asked Dec 07 '22 20:12

Beef


1 Answers

Basically, all those InterlockedXXX functions are more or less intrinsics that map to relatively few (typically one) assembly instructions. Such an operation cannot be interrupted and is thus said to be atomic (the atomicity is achieved at CPU level, at least if this is possible on the target platform).

A CRITICAL_SECTION is a synchronization primitive that can protect longer sections. It really does a lock and competing threads will be forced to wait until a thread releases ownership of the critical section.

Critical sections are OS primitives, but they are limited to a single process. Their big brother of a critical section under Windows is a Mutex, which can be used for cross-process synchronization.

Use the InterlockedXXX functions if you can (for example it makes no sense to use a full critical section object to protect a single counter). You may want to have a look at the various prototypes and their usage upfront. Many people use critical sections where a InterlockedCompareExchange would do ...

like image 77
Alexander Gessler Avatar answered Apr 13 '23 01:04

Alexander Gessler