gpt4 book ai didi

c++ - 同步访问返回值

转载 作者:IT老高 更新时间:2023-10-28 22:38:19 24 4
gpt4 key购买 nike

考虑以下 C++ 成员函数:

 size_t size() const
{
boost::lock_guard<boost::mutex> lock(m_mutex);
return m_size;
}

这里的目的不是同步对私有(private)成员变量m_size的访问,而只是为了确保调用者接收到一个有效的m_size值。目的是防止函数在返回 m_size 的同时某个其他线程正在修改 m_size

但是调用这个函数有没有潜在的竞争条件?我不确定这里的 RAII 样式锁是否足以防止竞争条件。假设在函数的返回值被压入堆栈之前调用了锁的析构函数?

我是否需要执行以下操作来保证线程安全?

 size_t size() const
{
size_t ret;

{
boost::lock_guard<boost::mutex> lock(m_mutex);
ret = m_size;
}

return ret;
}

最佳答案

您的两个示例构造都可以满足您的需求。标准中的以下信息支持您正在寻找的行为(即使在您的第一个示例中):

12.4/10 析构函数:

Destructors are invoked implicitly ... for a constructed object with automatic storage duration (3.7.2) when the block in which the object is created exits.

还有,6.6/2条跳转语句(其中return是其中之一):

On exit from a scope (however accomplished), destructors (12.4) are called for all constructed objects with automatic storage duration (3.7.2) (named objects or temporaries) that are declared in that scope, in the reverse order of their declaration. Transfer out of a loop, out of a block, or back past an initialized variable with automatic storage duration involves the destruction of variables with automatic storage duration that are in scope at the point transferred from but not at the point transferred to.

所以在 return 处,lock 变量在作用域内,因此没有调用 dtor。一旦执行了 return,就会调用 lock 变量的 dtor(从而释放锁)。

关于c++ - 同步访问返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3199995/

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