Advertisement
Guest User

Untitled

a guest
Oct 10th, 2022
61
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.48 KB | None | 0 0
  1.   // This wrapper allows you do something like:
  2.   //
  3.   //   ThreadSafeObject<std::map<std::string, std::string>> myMap;
  4.   //   ...
  5.   //   myMap.withLock()->emplace(key, value);
  6.   //
  7.   // instead of manually wrapping the race sensitive operation in a scope with std::lock_guard.
  8.   //
  9.   // Lock may be omitted when synchronization is not needed:
  10.   //
  11.   //   if(myMap->contains(something))
  12.   //     ...
  13.   //
  14.   // The underlying mutex may be used manually, to guard a sequence of operations for example:
  15.   //
  16.   //   std::lock_guard _(myMap.mx());
  17.   //   myMap->emplace(something);
  18.   //   myMap->...
  19.  
  20.   template<class T>
  21.   class ThreadSafeObject
  22.   {
  23.   public:
  24.     class WithLock
  25.     {
  26.     public:
  27.       WithLock(ThreadSafeObject<T> *tsobj)
  28.         : tsobj_(tsobj)
  29.       {
  30.         tsobj_->mx_.lock();
  31.       }
  32.  
  33.       WithLock(const WithLock &other) = delete;
  34.       WithLock(WithLock &&other) = delete;
  35.  
  36.       WithLock& operator=(const WithLock &other) = delete;
  37.       WithLock& operator=(WithLock &&other) = delete;
  38.  
  39.       ~WithLock()
  40.       {
  41.         tsobj_->mx_.unlock();
  42.       }
  43.  
  44.       T& operator*() { return tsobj_->obj_; }
  45.       T* operator->() { return &tsobj_->obj_; }
  46.    
  47.     private:
  48.       ThreadSafeObject<T> *tsobj_;
  49.     };
  50.  
  51.     WithLock withLock()
  52.     {
  53.       return WithLock(this);
  54.     }
  55.  
  56.     T& operator*() { return obj_; }
  57.     T* operator->() { return &obj_; }
  58.  
  59.     std::mutex& mx() { return mx_; }
  60.  
  61.   private:
  62.     T obj_;
  63.     std::mutex mx_;
  64.   };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement