Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // This wrapper allows you do something like:
- //
- // ThreadSafeObject<std::map<std::string, std::string>> 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 T>
- class ThreadSafeObject
- {
- public:
- class WithLock
- {
- public:
- WithLock(ThreadSafeObject<T> *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<T> *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_;
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement