gpt4 book ai didi

c++ - scoped_lock 的范围

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:45:57 25 4
gpt4 key购买 nike

我是多线程编程的新手。所以就我而言,我有一个 boost multi_index可以同时从多个线程到达的容器。我正在执行一些搜索和插入操作。

因此,当搜索以索引开始时,我不希望另一个线程插入新值。因为它可以改变索引并增加质量。所以我必须使用互斥体。

这么多人使用boost scoped_lock以此目的。我的问题只是 scoped_lock 的“范围”是什么?

假设我有一个这样的函数:

void A ()
{
myData data;
// prepare data here

// ******* 1 ********
B(data); // assume this perform some operations

}

void B (myData data)
{
// do some stuff with data
// ******* 2 ********
search(data);
}


void search(myData data)
{
// ******* 3 ********
// start searching the data here
}

所以我想从过程的开始获取锁,这意味着从过程 A。如果我把我的 boost::mutex::scoped_locklock(mutex);代码到标记为******* 1 ********的地方它是否也锁定 procedure B 中的进程和 procedure search还是我必须把锁放在里面 Bsearch还有吗? (到标有 2 和 3 的地方)。哪个是正确的位置 1、2、3 或全部?

顺便说一句,我的应用程序是单作者和多读者类型。所以shared_lock对我的情况有很大影响,还是可以使用 scoped_lock

注意:我在visual sturdio 2008环境下使用visual c++

谢谢...

最佳答案

boost::mutex::scoped_lock lock(mutex);

创建一个具有自动存储的对象(也就是一个常规的局部变量)。该对象在创建时锁定您传递给它的互斥锁,并在销毁时解锁它。由于该对象具有自动存储功能,因此当它超出范围时会被销毁(因此互斥量会被解锁)。

具体来说,这意味着,如果您将上面的 scoped_lock 语句放在 ******* 1 ********* 标记处在您的代码中,互斥量将一直保持到 A() 返回,因此 B 的执行也将受到锁的保护(在此上下文中)。

void A ()
{
myData data;
// prepare data here

boost::mutex::scoped_lock lock(mutex);
// whatever happens from here ....

doSomeStuff();

B(data); // assume this perform some operations

doMoreStuff();

// ... to here is protected by the lock
}

此编程习语名为 RAII,表示“资源获取即初始化”,您可以在此处了解更多信息:What is meant by Resource Acquisition is Initialization (RAII)?

旁注:从 C++11 开始,STL 现在包含互斥锁和锁,因此您无需为此使用 boost。等效语句是:

std::mutex a_mutex;
{
std::lock_guard<std::mutex> a_lock(a_mutex);

// mutex is locked until the end of this scope
}

关于c++ - scoped_lock 的范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21874083/

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