Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a mutex locker class in C++

This is what I have done so far:

class mutexLocker
{
    private:
    /* Declaration of a Mutex variable `mutexA`. */
    pthread_mutex_t &mutexA;

    /* `mutexStatus` holds the return value of the function`pthread_mutex_lock `. 
    This value has to be returned to the callee so we need to preserve it in a class
    variable. */
    int             mutexStatus;

    /* We need to decide how to deal with the situation when one thread tries to lock then
    mutex repeatedly. If the mutex is of type recursive, then there won't be any problem for 
    sure, but otherwise the case may result in a deadlock. */
    pthread_t       calleeThreadId;

    public:
    /* Constructor attempts to lock the desired mutex variable. */
    mutexLocker (pthread_mutex_t argMutexVariable, pthread_t threadId) 
    : mutexA (argMutexVariable, calleeThreadId)
    {
        /* Return value is needed in order to know whether the mutex has been 
        successfully locked or not. */
        int mutexStatus = pthread_mutex_lock (&argMutexVariable);
    }

    /* Since the constructor can't return anything, we need to have a separate function
    which returns the status of the lock. */
    int getMutexLockStatus ()
    {
        return mutexStatus;
    }

    /* The destructor will get called automatically whereever the callee's scope ends, and
    will get the mutex unlocked. */
    ~mutexLocker ()
    {
        pthread_mutex_unlock (&mutexA);
    }
};

What other functionalities should be provided in a DIY mutex locker class?

like image 853
Aquarius_Girl Avatar asked Feb 16 '26 01:02

Aquarius_Girl


1 Answers

I fully agree with Slavik81's comments about not creating functionality you don't have a use case for.

Nevertheless referencing the Boost implementations of lock classess may be a good starting point in terms of understanding common requirements of their interfaces: http://www.boost.org/doc/libs/1_42_0/doc/html/thread/synchronization.html#thread.synchronization.locks

In terms of the standard C++11 introduces std::lock_guard: http://en.cppreference.com/w/cpp/thread/lock_guard

like image 147
Graeme Avatar answered Feb 18 '26 14:02

Graeme



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!