开发者

Difference between interlocked variable access AND critical sections interlocked increment

开发者 https://www.devze.com 2023-03-15 14:05 出处:网络
can someone help explain the different between interlocked variable access AND critical sections interlocked incr开发者_运维技巧ement in c++? thanks, much appreciated, in advance.Basically, all those

can someone help explain the different between interlocked variable access AND critical sections interlocked incr开发者_运维技巧ement in c++? thanks, much appreciated, in advance.


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 ...


A critical section is a lock. An InterlockedXxx function call is an atomic operation -- no lock. You could build either in terms of the other, but in practice they have very different performance characteristics (Interlocked functions are usually faster).


Basically, the Interlocked functions are the same concept as a critical section, but they're implemented in hardware for certain operations - lock, operate, unlock. This can make them much faster, but limits their applicability. Critical sections are much more generic, but the relative cost of using one is higher. They also have problems like race conditions and deadlocks.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号