When working with a mutex-protected variable, you often need to read or modify its value while holding the lock, but then operate on the value outside the lock to minimize contention. While the traditional approach involves copying the value within a locked scope, using an immediately-invoked lambda or helper function can streamline this process, enabling efficient copy elision or move semantics to optimize performance.
A Pattern for Obtaining a Single Value While Holding a Lock
by Raymond Chen
From the article:
It is often the case that you have a mutex or other lockable object which protects access to a complex variable, and you want to read the variable’s value (possibly modifying it in the process) while holding the lock, but then operate on the value outside the lock.
The traditional way is to do something like this:
// Assume we have these member variables std::mutex m_mutex; Widget m_widget; // Get a copy of the widget Widget widget; { auto guard = std::lock_guard(m_mutex); widget = m_widget; } ⟦ use the variable "widget" ⟧This does suffer from the problem of running the
Widget
constructor for an object that we’re going to overwrite anyway. The compiler will also have to deal with the possibility that thelock_
constructor throws an exception, forcing the destruction of a freshly-constructedguard Widget
.
Add a Comment
Comments are closed.