Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

custom RAII C++ implementation for scoped mutex locks

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 create a mutex locks. Upon class destruction the mutex is unlocked.

Any implementation available? I don't want to re-invent the wheel.

I need to use pthreads.

  • resource acquisition is initialization == “RAII”
like image 348
cateof Avatar asked Nov 02 '11 07:11

cateof


1 Answers

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;
};
like image 139
sehe Avatar answered Oct 06 '22 10:10

sehe