c++ - 锁定方案黑客

标签 c++ synchronization

这看起来怎么样:

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/

相关文章:

c++ - 神经网络为不同的输入提供相同的输出,不学习

c++ - C++ 在基于 Intel 的系统上使用的 float 的二进制格式是什么?

c - 多种资源的细粒度锁定算法

c++ - 如何使用 UART 板从 DS​​18B20 读取温度

c++ - Solaris:libSTLPort.so 与 libCstd.so 的二进制兼容性?

android - JNI编码和使用JNI连接到java的c/c编码之间的区别

android - 等待另一项 Activity 的结果

java - java中同步块(synchronized block)的部分执行

swift - 通过 Realm 框架如何快速与网络服务器同步(更新和下载)?

c++ - C++应用多线程中的Lock方法