Home > Articles > Programming

  • Print
  • + Share This
From the author of Specialized Lock Types

Specialized Lock Types

Most threading systems include some special kinds of locks. The POSIX thread API contains one that is particularly useful: read-write locks. You typically end up implementing something like this yourself if you don't get one from your standard APIs.

Read-write locks are designed for the situation in which some tasks can be performed in parallel, but others can't. Reading and writing to a complex data structure is a typical example, hence the name.

Consider a structure like a balanced tree. Any number of threads can simultaneously read values from the tree; however, inserting or removing a node may result in some readers following dangling pointers.

Read-write locks are designed to address this issue. When you acquire the lock, you do so as either a reader or a writer. Any number of readers can hold the lock at the same time, but only one writer. If a writer holds the lock, no reader can.

These locks are typically designed to be very fast in read mode, which is sometimes called shared mode (in the Win32 API, for example). If you have a resource that supports multiple readers but only one writer, a read-write lock will give you a performance advantage versus using a mutex and only allowing one reader or one writer. Because the API version is typically heavily optimized, it's also likely to be much faster than rolling your own.

  • + Share This
  • 🔖 Save To Your Account