gpt4 book ai didi

c++ - 锁定方案黑客

转载 作者:行者123 更新时间:2023-11-28 08:27:03 25 4
gpt4 key购买 nike

这看起来怎么样:

class HugeHack
{
HugeHack() : m_flag( false ) { }

void Logout( )
{
boost::lock_guard< boost::mutex > lock( m_lock );
m_flag = true;

// do stuff that in a perfect world would be atomic with library call and onLogout

// call a library function that waits for a thread to finish, that thread calls my onLogout() function before it dies

m_flag = false;
}


void onLogout()
{
boost::unique_lock< boost::mutex > l( m_lock, boost::defer_lock_t );
if( ! m_flag )
l.lock();

// do stuff

}



boost::mutex m_lock;
bool m_flag;
};

该标志仅在注销运行时为真,注销合法地等待调用 onLogout 的线程结束,因此除非其他人可以调用 onLogout...(不能完全确定我正在使用的不是我的库 -快速修复)

我不确定我是否在那里正确使用了唯一锁,如果没有,目标只是有条件地锁定锁(同时保持作用域锁定语义)。

最佳答案

问题是,如果你在没有锁定互斥量的情况下读取 m_flag,你可能会看到 m_flag 为 false,即使实际上它是 true,并且 Logout 正在操作中。锁定互斥量会产生一个内存栅栏,这对于确保适当的内存可见性至关重要。顺便说一句,stijn 是对的 - 如果这就是您所追求的,您可以放弃 m_flag 并改用 try_lock,如下所示:

boost::mutex::scoped_try_lock l( m_lock );
if ( l )
// lock succeeded

关于c++ - 锁定方案黑客,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3636869/

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