在C++中创建互斥锁更衣类
Creating a mutex locker class in C++
这是我到目前为止所做的:
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
.
最后,在 中通过引用传递互斥锁(尽管我认为这是一个错字)。
相关文章:
- 如何创建一个CMake变量,除非显式重写,否则使用默认值
- 使用std::multimap迭代器创建std::list
- 在全局变量中保存类的实例以重新创建类(创建"backup")
- 使用CMake创建QML插件
- 如何在c++中为模板函数实例创建快捷方式
- 在C++中,是否可以基于给定的标识符创建基类的新实例,反之亦然
- 创建一个函数以在输入为负数或零时输出字符串.第一次执行用户定义的函数
- OpenCV EqualizeHist()从彩色图像创建黑白图像
- 试图在visual studio上用C++创建一个桌面应用程序
- std::threads可以从Windows DLL中的全局变量创建/销毁吗?
- 如何在C++20中创建模板别名的推导指南
- 如何为模板化对象创建模板向量?VS正在投掷C3203
- 如何创建一个空的全局类并在启动时实例化它
- 无法创建抽象类的实例
- 链接到自行创建的dll失败
- 为什么我不能在不创建字符串变量的情况下使用函数的字符串输出
- 有没有一种方法可以创建一个带有哈希表的数据库,该哈希表具有恒定时间查找功能
- 如何在C++类内存结构中创建"spacer"?
- 终端不会为C++文件创建.exe文件吗
- 在createdialog创建的窗口中捕获用于编辑控件的OnMouseMove消息