3 ms·
A critical section is code that accesses mutable shared data in a non-atomic way (i.e. as several steps, the classic example is: fetch data into a register, pro
by wpollock 1y ago
A critical section is code that accesses mutable shared data in a non-atomic way (i.e. as several steps, the classic example is: fetch data into a register, process that data, store the result back into memory). A lock is a mechanism that protects such data by preventing other code (or other threads running the same code) from accessing that data until the critical section completes.
Locks come in several types. A developer picks one type depending on the use of the protected data; for example, exclusive, reader-writer, and others.
Locks are great at preventing data corruption and data loss, but come with issues. They can hurt performance, can cause "liveness" and other issues, and are usually "advisory" ("mandatory" locks which are enforced by the OS are rarely available) so developers must remember to protect data by using locks around every critical section.
Modern hardware includes support for many lock-free mechanisms that can greatly reduce the need for locks.