c – 返回对象值时的互斥锁

如果我理解C编译器如何处理局部变量,那么IsShutdownInProgress()不需要任何锁定,因为shutdownInProgress静态变量将被放置在堆栈上.我对么?
class MyClass
{
    private:
        // Irrelevant code commented away
        static pthread_mutex_t mutex;
        static bool shutdownInProgress;
    public:
        static void ShutdownIsInProgress()
        {
            pthread_mutex_lock(mutex);
            shutdownInProgress = true;                  
            pthread_mutex_unlock(mutex);
        }

        static bool IsShutdownInProgress()
        {
            // pthread_mutex_lock(mutex);
            // pthread_mutex_unlock(mutex);
            return shutdownInProgress;
        }
}

解决方法

Am I correct?

不会.这会将其复制回来;但读取它以使该副本不同步将导致数据竞争,具有未定义的行为.您需要在锁定互斥锁的情况下制作本地副本:

static bool IsShutdownInProgress()
{
    pthread_mutex_lock(mutex);
    bool result = shutdownInProgress;
    pthread_mutex_unlock(mutex);
    return result;
}

或者,使用不易出错的RAII锁定类型:

static bool IsShutdownInProgress()
{
    lock_guard lock(mutex);
    return shutdownInProgress;
}

在C 11中,您可以考虑使用std :: atomic< bool>为了更方便,也许更有效,从多个线程访问简单类型.

相关文章

本程序的编译和运行环境如下(如果有运行方面的问题欢迎在评...
水了一学期的院选修,万万没想到期末考试还有比较硬核的编程...
补充一下,先前文章末尾给出的下载链接的完整代码含有部分C&...
思路如标题所说采用模N取余法,难点是这个除法过程如何实现。...
本篇博客有更新!!!更新后效果图如下: 文章末尾的完整代码...
刚开始学习模块化程序设计时,估计大家都被形参和实参搞迷糊...