CIS: “Protecting” code in stead of data

The Windows API contains a synchronization primitive that is a mutual exclusion device, but is also a colossal misnomer. I mean, of course, the CRITICAL_SECTION.

The “critical section” describes a piece of code that accesses a shared resource — shared between threads or processes. While such code should be analyzed and well-understood, and is indeed critical in a sense, it’s the data that needs to be protected from concurrent access, if necessary.

Much confusion has arisen from the name CRITICAL_SECTION: more than once, I’ve seen them being used to “protect” the code itself, rather than the data.

Using a ScopedLock class, such as the following, does two things:

  1. the class’ name makes it clear that it’s a lock, so something needs locking
  2. it takes care of exception-safety and prevents lock leaks

(Of course, a POSIX version of the same class does the same thing, but the POSIX mutex is better named).

A more elaborate solution would be to create a Mutex class to encapsulate the CRITICAL_SECTION, allowing newbies to google for “mutex”…

About rlc

Software Analyst in embedded systems and C++, C and VHDL developer, I specialize in security, communications protocols and time synchronization, and am interested in concurrency, generic meta-programming and functional programming and their practical applications. I take a pragmatic approach to project management, focusing on the management of risk and scope. I have over two decades of experience as a software professional and a background in science.
This entry was posted in Common Issues with Synchronization and tagged , . Bookmark the permalink.