gpt4 book ai didi

c++ - 范围锁定如何工作?

转载 作者:可可西里 更新时间:2023-11-01 18:03:04 25 4
gpt4 key购买 nike

我正在学习 C++,我发现作用域锁的源代码非常简单。 .它是如何工作的,这是“资源获取是实例化”(RAII)的一个例子吗?

最佳答案

下面是说明作用域锁的小代码:

 void do_something()
{
//here in the constructor of scoped_lock, the mutex is locked,
//and a reference to it is kept in the object `lock` for future use
scoped_lock lock(shared_mutex_obj);

//here goes the critical section code

}//<---here : the object `lock` goes out of scope
//that means, the destructor of scoped_lock will run.
//in the destructor, the mutex is unlocked.

阅读评论。这解释了 scoped_lock 的工作原理。

下面是 scoped_lock 的典型实现方式(最少代码):

class scoped_lock : noncopyable
{
mutex_impl &_mtx; //keep ref to the mutex passed to the constructor
public:
scoped_lock(mutex_impl & mtx ) : _mtx(mtx)
{
_mtx.lock(); //lock the mutex in the constructor
}
~scoped_lock()
{
_mtx.unlock(); //unlock the mutex in the constructor
}
};

关于c++ - 范围锁定如何工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14276508/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com