// This wrapper allows you do something like: // // ThreadSafeObject> myMap; // ... // myMap.withLock()->emplace(key, value); // // instead of manually wrapping the race sensitive operation in a scope with std::lock_guard. // // Lock may be omitted when synchronization is not needed: // // if(myMap->contains(something)) // ... // // The underlying mutex may be used manually, to guard a sequence of operations for example: // // std::lock_guard _(myMap.mx()); // myMap->emplace(something); // myMap->... template class ThreadSafeObject { public: class WithLock { public: WithLock(ThreadSafeObject *tsobj) : tsobj_(tsobj) { tsobj_->mx_.lock(); } WithLock(const WithLock &other) = delete; WithLock(WithLock &&other) = delete; WithLock& operator=(const WithLock &other) = delete; WithLock& operator=(WithLock &&other) = delete; ~WithLock() { tsobj_->mx_.unlock(); } T& operator*() { return tsobj_->obj_; } T* operator->() { return &tsobj_->obj_; } private: ThreadSafeObject *tsobj_; }; WithLock withLock() { return WithLock(this); } T& operator*() { return obj_; } T* operator->() { return &obj_; } std::mutex& mx() { return mx_; } private: T obj_; std::mutex mx_; };