3

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

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 互斥锁储物柜类中还应该提供哪些其他功能?

4

3 回答 3

5

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

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

于 2012-08-16T06:24:59.883 回答
5

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

尽管如此,参考锁类的 Boost 实现可能是了解其接口的常见要求的一个很好的起点:http: //www.boost.org/doc/libs/1_42_0/doc/html/thread/synchronization.html#线程同步锁

在标准 C++11 方面介绍std::lock_guardhttp ://en.cppreference.com/w/cpp/thread/lock_guard

于 2012-08-16T06:41:14.077 回答
1

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

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

  • 您可能需要额外的错误支持,具体取决于您处理错误的方式。例如,如果您的团队在锁失败时抛出异常,则该类可以创建并抛出异常。
  • 作为诊断,您可能希望验证客户端测试获取成功(例如assert,如果他们从未验证锁定成功,则在 dtor 中)。
  • 您可能需要“重试”采集功能。最好在抛出异常之前重试,imo。就个人而言,我只是认为这是程序员的错误EBUSY——不要持有长锁!
  • 还要把你的东西藏pthread_mutex_t在课堂上——禁止复制、分配等等。把它交给你的储物柜。
  • 一些客户可能想要一种简单的方法来测试成功,而不是评估状态。取决于你如何使用它。
  • 如果您没有获得锁,请不要在 dtor 中解锁
  • 检查解锁结果。确定这种情况下的错误处理。

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

  • 没有复制。显式删除复制 ctor 表达了意图。
  • 删除operator=——表达意图。
  • 删除动作
  • calleeThreadId:删除,除非你觉得有用。具体来说,考虑一下你将如何实际实现你提出的这个错误检测——储物柜似乎是存放数据的错误位置,imo。我更喜欢将这些储物柜保持在最小、集中和简单的位置。
  • 加倍努力:防止堆分配;例如,删除运算符 new/delete 的主要变体。
  • 如果您不重试,则状态可能为const.
  • threadID,如果您决定保留它,也可以是const.

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

于 2012-08-16T07:03:54.263 回答