FOLLY: Synchronized.h (1)

FOLLY: Synchronized.h (1)


A straightforward abstraction for mutex-based concurrency is presented in folly/Synchronized.h. It swaps out complicated, cumbersome, and downright incorrect code with straightforward structures that are simple to understand and nearly impossible to do wrong.

Introduction to folly/Synchronized.h

The rewrite accomplishes the necessary tasks with optimum efficiency: it gets the lock connected to the RequestQueue object, writes to the queue, and then promptly releases the lock.

On the surface, that doesn't seem like much to brag about or like a significant improvement over the situation before.

• As opposed to earlier, the data and the mutex guarding it are now tightly bound together.

• It is practically impossible to access the queue without getting the right lock, so you couldn't use requestQueue_ if you didn't have it.

• The lock is not held for activities that do not require it; rather, it is released immediately following the insert operation.

Synchronized offers a number of alternatives for performing multiple tasks while holding the lock if you need to.

A LockedPtr object that can be kept in a variable is returned by the wlock() method, or lock() if you have a non-shared mutex type. Similar to a std::unique lock, the lock will be held for as long as this object is present.

Similar to wlock(), the rlock() function acquires a shared lock as opposed to an exclusive lock.

Every time you store a LockedPtr object, we advise opening a new nested scope explicitly to assist distinguish the vital area visibly and to make sure the LockedPtr is removed as soon as it is no longer required.

The withWLock() method has the advantage of making the important area utilise a new scope, which makes it more evident in the code and encourages writing code that releases the lock as quickly as feasible.