在c++并发中使用互斥锁
using mutex in c++ concurrency
尝试用c++理解并发编程的细节。遇到了这段代码,却无法理解其中一行代码。附件是详细信息:
template<typename T>
class threadsafe_stack
{
private:
std::stack<T> data;
mutable std::mutex m;
public:
threadsafe_stack(){}
threadsafe_stack(const threadsafe_stack& other)
{
std::lock_guard<std::mutex> lock(other.m);
//////////////////why <1>locking other.m not this->m <2> or locking both
data=other.data;
}
// some other codes
}
这是因为threadsafe_stack
类的this
实例是第一次被构造,所以你可以确定没有其他人正在访问它的字段,所以它不需要使用this->mutex
。但是,此时其他人可能正在使用other
实例,因此使用该互斥锁来保护other
的data
字段免受并发访问是一个好主意。
也就是说,复制构造函数,你看到的代码,是在基于其他实例的对象构造时调用的,例如:
threadsafe_stack copy_of_stack{ original_stack };
现在,在复制构造函数的执行完成之前,任何人都不能在copy_of_stack
实例的上下文中调用方法。
每个threadsafe_stack
的互斥锁字段的目的是防止互斥锁所属实例的内容被并发访问。
现在,假设有其他线程在original_stack
实例上操作:
while (true)
{
original_stack.push(123);
std::this_thread::sleep_for(std::chrono::seconds(1));
}
,其中push
方法看起来像这样:
void threadsafe_stack<T>::push(const T& value)
{
std::lock_guard<std::mutex> lock{ this->m };
data.push(value);
}
可以看到,每个push
操作都保护它自己的 data
字段。字段data
的同一个实例正在被copy_of_stack
实例的复制构造函数访问。使用同一个互斥量使得对data
字段的访问是互斥的。换句话说:在data = other.data;
中,此时没有其他人可以访问data
,但是有人可以访问other.data
,这就是为什么我们只锁定一个(other
的)互斥锁。
相关文章:
- 控制允许动态运行c++的并发操作数
- 节俭并发:未解决的外部问题
- 并发/多线程:是否可以以这种方式生成相同的输出?
- 用于在并发环境中访问 MMIO 的软件模式
- C++中的并发哈希表
- 提升 asio 并发计时器取消问题与链
- C++具有基元类型的并发队列
- 使用简单两相锁定的并发程序
- C++ 按引用或值推送的并发队列
- 允许多个互斥锁所有者或指定数量的并发代码执行
- 琐碎并发代码的吞吐量不会随着线程数量的增加而增加
- 由并发无序映射查找线程调用的函数是否安全?
- 在迭代期间并发修改映射
- 并发安全堆栈接口方法:正确与否?
- 内存模型和并发
- 重塑Microsoft的并发::d iagnostic::span,也可以检测外部跨度
- 如何在 qt 中从另一个线程运行 qt并发时关闭程序
- 并发问题:如何只有一个线程通过关键部分
- Qt并发错误:用作初始值设定项的数组
- 如何使用 c++ 实现并发文件/文本编辑?