在C++中创建互斥锁更衣室类

Aqu*_*irl 3 c++ multithreading mutex pthreads

这是我到目前为止所做的:

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);
    }
};
Run Code Online (Sandbox Code Playgroud)

DIY互斥锁柜台应该提供哪些其他功能?

cgm*_*gmb 5

你正在接近这一点.您编写代码来解决您遇到的问题.不要编写代码来解决你没有的问题." 你不需要它 "是一个很好的原则.

除非您遇到可以用它们解决的问题,否则不应提供其他功能.鉴于你没有提到任何问题,我认为你没有这样的问题.因此,还不应该添加其他功能.


Gra*_*eme 5

我完全同意Slavik81关于不创建你没有用例的功能的评论.

然而,在理解其接口的常见要求方面,引用锁定classess的Boost实现可能是一个很好的起点:http://www.boost.org/doc/libs/1_42_0/doc/html/thread/synchronization.html# thread.synchronization.locks

就标准C++ 11介绍而言std::lock_guard:http://en.cppreference.com/w/cpp/thread/lock_guard