The difference between mutually blocked variable access and critical sectors with blocking

can anyone help explain the difference between blocked access to a variable and critical sections with increment lock in C ++? Thank you, highly appreciated in advance.

+4
source share
3 answers

In principle, all of these InterlockedXXX functions are more or less internal, which are compared with relatively small (usually one) assembly instructions. Such an operation cannot be interrupted and, therefore, is considered atomic (atomicity is achieved at the CPU level, at least if it is possible on the target platform).

A CRITICAL_SECTION is a synchronization primitive that can protect longer sections. In fact, locking and competing threads will have to wait until the thread releases ownership of the critical section.

Critical sections are OS primitives, but they are limited to one process. Their older brother in the critical section under Windows is Mutex , which can be used for the cross-synchronization process.

Use InterlockedXXX functions if you can (for example, it makes no sense to use the full critical section object to protect a single counter). You might want to take a look at the various prototypes and their use in advance. Many people use critical sections where InterlockedCompareExchange will be ...

+8
source

The critical section is locking. Calling the InterlockedXxx function is an atomic operation - without blocking. You can build either in terms of another, but in practice they have very different performance characteristics (blocked functions are usually faster).

+3
source

Basically, locking functions are the same concept as the critical section, but they are implemented in hardware for certain operations - locking, working, unlocking. This can make them much faster, but limits their applicability. Critical sections are much more general, but the relative cost of using them is higher. They also have problems, such as race conditions and dead ends.

+3
source

All Articles