I have a pool of threads that asynchronously acquire and execute tasks in a queue. Some of these tasks operate over some shared resources. I would like to:

  1. Provide a contract that separates shared resources from task-specific resources
  2. Through this contract, ensure that all shared resources are guarded by an appropriate lock (e.g., a mutex)

One option is a generalization of the solution provided here. You provide some sort of SharedResource<T> class template. An instance of SharedResource<T> owns a shared resource of type T along with a mutex. It exposes some acquire() method that locks the internal mutex and returns a LockedResource<T> object, which holds the lock and a reference to the shared resource. On destruction, the LockedResource<T> object releases its lock. LockedResource<T> forwards all calls to the underlying T resource (e.g., by implementing operator->()). To support shared ownership of the underlying resource across tasks, you could also wrap the SharedResource<T> object's resource and mutex in an automatic reference counter (e.g., a std::shared_ptr<std::tuple<T, std::mutex>>). As intended, the effect of this solution is that it is necessary to acquire the lock prior to accessing the underlying resource.

This all seems very doable. Yet, it also seems like a convenient solution to a common problem, which makes me think it's probably already been solved by some library. Does the C++ standard library or Boost provide anything like this? If not, do any other libraries come to mind?

  • Better ask your question here: stackoverflow.com May 18, 2023 at 19:05
  • 1
    @RomeoNinov Why? I'm not asking how to implement a solution to a problem. I'm asking for existing software that implements a known solution. This is a classic software recommendation question. May 18, 2023 at 19:12
  • Here's a source explicitly stating that this is the appropriate site to ask if a library exists to solve a problem, and that this question is off-topic for SO. Here's Robert Harvey's answer to the same question. May 18, 2023 at 19:17

1 Answer 1


A little late to this, but anyone finding this thread via Google should know that there is exactly this being adopted by the C++ core library, synchronized_value<T>:

The basic idea is that synchronized_value<T> stores a value of typeT and a mutex.The apply() function then provides a means of accessing the stored value with the mutex locked, automatically unlocking the mutex afterwards.

GCC 13 already contains an implementation of this you can import from <experimental>

  • 1
    It's never too late to provide a useful answer Sep 4, 2023 at 18:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.