锁定方案是一种黑客攻击
看起来怎么样:
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;
};
该标志仅在 Logout 运行时为 true,Logout 合法地等待调用 onLogout 的线程死亡,所以除非其他人可以调用 onLogout...(不能完全确定不是我正在使用的库- QuickFix)
我不确定我是否正确使用了唯一锁,如果没有,目标只是有条件地锁定锁(同时维护范围锁定语义)。
How's this look:
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;
};
The flag is true ONLY while Logout is running, Logout legitimately waits for a thread to die that calls onLogout, so unless someone else can call onLogout... (can't be totally sure not my library I'm using - QuickFix)
I'm not sure I'm using the unique lock correctly there, if not, the goal is only to conditionally lock the lock (while maintaining scoped locking semantics).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
问题是,如果您在没有锁定互斥锁的情况下读取 m_flag,您可能会看到 m_flag 为 false,即使实际上它是 true,并且 Logout 正在操作中。锁定互斥体会产生内存栅栏,这对于确保正确的内存可见性至关重要。顺便说一句 stijn 是对的 - 如果这就是你所追求的,你可以放弃 m_flag 并使用 try_lock 代替,如下所示:
The problem is that if you read m_flag without locking the mutex, you might see m_flag be false even if in reality it is true, and Logout is in the middle of operation. Locking the mutex issues a memory fence, which is essential to ensure proper memory visibility. And BTW stijn is right - if this is all you are after, you can ditch m_flag and use try_lock instead, like this:
听起来您想要做的是在等待线程终止(并调用
onLogout
)时释放 Logout 中的锁。因此,请改为这样做,然后无条件地在onLogout
中获取锁定。It sounds like what you want to do is release the lock in
Logout
at the point you are waiting for the thread to terminate (and callonLogout
). So do that instead, then unconditionally take the lock inonLogout
.