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

Creating a mutex locker class in C++

本文关键字:C++ 创建      更新时间:2023-10-16

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

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);
    }
};

DIY 互斥锁更衣柜类中还应提供哪些其他功能?

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

尽管如此,引用锁类的 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:

你有点

倒退了。您编写代码来解决您面临的问题。不要编写代码来解决您没有的问题。"你不需要它"是一个很好的原则。

除非您有可以用它们解决的问题,否则不应提供其他功能。我假设你没有这样的问题,因为你没有提到任何问题。因此,不应添加其他功能。

首先,Graeme 和 Slavik81 的答案都非常好(+1)。

现在,至于要添加的内容:

  • 您可能需要其他错误支持,具体取决于您处理错误的方式。例如,如果团队在锁定失败时引发异常,则类可以创建并引发异常。
  • 作为诊断,您可能需要验证客户测试的获取是否成功(例如 assert 在 dtor 中,如果他们从未验证过锁定是否成功)。
  • 您可能需要"重试"获取功能。 最好在引发异常之前重试,IMO。就我个人而言,我只是认为这是程序员的错误,如果EBUSY - 不要持有长锁!
  • 还要将您的pthread_mutex_t藏在课堂上 - 禁止复制、作业等。 把它交给你的储物柜。
  • 一些客户可能需要一种简单的方法来测试成功,而不是评估状态。 取决于您如何使用它。
  • 如果您没有获得锁,请不要在 DTOR 中解锁
  • 检查解锁的结果。 确定此方案中的错误处理。

也许更重要的是 - 确定要删除的内容:

  • 不复制。显式删除复制 CTOR 表示意图。
  • 删除operator= -- 表达意图。
  • 删除移动
  • calleeThreadId:删除,除非你觉得有用。 具体来说,考虑一下您将如何实际实现您提出的此错误检测 - 储物柜似乎是数据的错误位置,IMO。 我更喜欢将这些储物柜保持最小小、专注和简单。
  • 额外里程:防止堆分配;例如,删除运算符 new/delete 的主要变体。
  • 如果不重试,则状态可能为 const
  • 线程 ID,如果您决定保留它,也可以const .

最后,在 中通过引用传递互斥锁(尽管我认为这是一个错字)。