custom RAII C++ implementation for scoped mutex locks

前端 未结 1 1661
無奈伤痛
無奈伤痛 2021-02-02 00:08

I cannot use boost or the latest std::thread library. The way to go is to create a custom implementation of a scoped mutex.

In a few words when a class instance is crea

相关标签:
1条回答
  • 2021-02-02 01:00

    Note This is an old answer. C++11 contains better helpers that are more platform independent:

    • std::lock_guard
    • std::mutex, std::timed_mutex, std::recursive_mutex, std::recursive_timed_mutex

    And other options like std::unique_lock, boost::unique_lock

    Any RAII tutorial will do.

    Here's the gist: (also on http://ideone.com/kkB86)

    // stub mutex_t: implement this for your operating system
    struct mutex_t 
    { 
        void Acquire() {} 
        void Release() {} 
    };
    
    struct LockGuard
    {
         LockGuard(mutex_t& mutex) : _ref(mutex) 
         { 
             _ref.Acquire();  // TODO operating system specific
         }
    
         ~LockGuard() 
         { 
              _ref.Release(); // TODO operating system specific
         }
       private:
         LockGuard(const LockGuard&); // or use c++0x ` = delete`
    
         mutex_t& _ref;
    };
    
    int main()
    {
        mutex_t mtx;
    
        {
            LockGuard lock(mtx);
            // LockGuard copy(lock); // ERROR: constructor private
            // lock = LockGuard(mtx);// ERROR: no default assignment operator
        }
    
    }
    

    Of course you can make it generic towards mutex_t, you could prevent subclassing. Copying/assignment is already prohibited because of the reference field

    EDIT For pthreads:

    struct mutex_t
    {
        public:
            mutex_t(pthread_mutex_t &lock) : m_mutex(lock) {}
    
            void Acquire() { pthread_mutex_lock(&m_mutex);   }
            void Release() { pthread_mutex_unlock(&m_mutex); }
        private:
            pthread_mutex_t& m_mutex;
    };
    
    0 讨论(0)
提交回复
热议问题