c++通过对不同实例的引用传递互斥锁
C++ Pass Mutex By Reference for Different Instances
我想在一个类的不同实例之间共享一个互斥锁,这些实例的函数作为线程运行。我这样写对吗?(我认为我不需要使用shared_mutex,尽管这可能是更好的实践。我要用同样的方式传递它吗?)
class A
{
public:
// Execute some work that locks some piece of data by acquiring the mutex.
void execute(std::mutex & myMutex);
}
class B
{
public:
void execute(std::shared_ptr<A> a)
{
// Create the Threads for execution.
// Changed to correct syntax.
std::thread t1(&B::runThread, this, a);
std::thread t2(&B::runThread, this, a);
t1.join();
t2.join();
};
void runThread(std::shared_ptr<A> a)
{
a->execute(std::ref(theMutex));
}
private:
// The Mutex to share with the threads.
std::mutex theMutex;
}
首先,所发布的代码无法编译:B::runThread()
是非static
成员,因此接受隐式对象作为参数。您需要使用如下命令创建线程:
std::thread t(&B::runThread, this, a);
假设B::theMutex
在使用A::execute()
时适当地保护了多线程之间共享的资源,那么在不同线程之间共享互斥锁的方法就是互斥锁的用途。由于这个问题缺乏任何细节,因此无法回答互斥锁是否是合适的同步原语:根据A::execute()
中的实际使用情况,其他方法可能更适合避免序列化,死锁等。
使用std::shared_mutex
基本上在所有情况下都是错误的方法,当然不是"更好的做法"。std::shared_mutex
实际上导致更好的方法的情况非常罕见。在实践中,我从未见过使用std::shared_mutex
之类的东西会提高性能的情况(我没有在实际情况中看到std::shared_mutex
,但我经常遇到POSIX计数器部分或其包装器)。相反,它总是导致比使用普通std::mutex
更差的性能,并且它有极其糟糕的最坏情况:当有大量更改(即排他锁)时,它经常导致整个系统的严重停滞。
相关文章:
- 对显式实例化的模板函数的未定义引用
- 重载运算符*以获取对另一个类的实例的引用
- 为什么我不能引用指向实例化对象的函数的指针?
- <Base> <Derived> 具有相同原始指针共享引用的 shared_ptr 和 shared_ptr 实例是否计数?
- 返回引用实例和非引用实例(return mystr & vs mystr)之间的区别是什么?
- 请参阅在 Visual Studio 2019 中捕获 std::exception 时对函数模板实例化消息的引用
- 将元组和整型实例合并到引用元组中
- C++ 为什么在定义的编译和链接之前引用外部实例的程序
- 是否允许使用初始值设定项列表将const数组引用实例化为构造函数参数
- 引用的静态强制转换强制模板实例化,其中不完整的类型很好
- 为什么不能在实例化对基类的引用的同时实例化指向派生类的指针?
- 非类型引用参数可以在运行时修改,这是否意味着模板可以在运行时实例化?
- 超出返回引用的单一实例生存期
- 反向函数不反转类实例化的引用字符串
- 通过引用将私有类实例传递到另一个类 C++ 的"get"函数中
- 多个实例保存对unique_ptr的引用
- 类模板实例化和通用引用
- 对Singleton的未定义引用::实例
- 为构造函数初始化引用实例变量提供默认值
- 在其构造函数中引用实例