How can I create a smart pointer that locks and unlocks a mutex?

前端 未结 3 468
迷失自我
迷失自我 2021-01-01 19:51

I have a threaded class from which I would like to occasionally acquire a pointer an instance variable. I would like this access to be guarded by a mutex so that the thread

3条回答
  •  既然无缘
    2021-01-01 20:19

    I'm not sure if there are any standard implementations, but since I like re-implementing stuff for no reason, here's a version that should work (assuming you don't want to be able to copy such pointers):

    template
    class locking_ptr
    {
    public:
      locking_ptr(T* ptr, mutex* lock)
        : m_ptr(ptr)
        , m_mutex(lock)
      {
        m_mutex->lock();
      }
      ~locking_ptr()
      {
        if (m_mutex)
          m_mutex->unlock();
      }
      locking_ptr(locking_ptr&& ptr)
        : m_ptr(ptr.m_ptr)
        , m_mutex(ptr.m_mutex)
      {
        ptr.m_ptr = nullptr;
        ptr.m_mutex = nullptr;
      }
    
      T* operator ->()
      {
        return m_ptr;
      }
      T const* operator ->() const
      {
        return m_ptr;
      }
    private:
      // disallow copy/assignment
      locking_ptr(locking_ptr const& ptr)
      {
      }
      locking_ptr& operator = (locking_ptr const& ptr)
      {
        return *this;
      }
      T* m_ptr;
      mutex* m_mutex; // whatever implementation you use
    };
    

提交回复
热议问题