使用互斥量,mvsc2017构建,在release模式下,互斥量会导致程序崩溃

问题描述 投票:0回答:1

我使用qt5开发环境,使用互斥量,mvsc2017构建,我在debug模式下不会使程序崩溃,但在release模式下,互斥量会导致程序崩溃

#pragma once
#include <mutex>
std::mutex g_initMutex;
class Config
{
private:
    Config()
    {
    }

    Config(const Config &) = delete;
    Config &operator=(const Config &) = delete;

    static std::mutex* getInitMutex() {
        static std::mutex* const initMutex = new std::mutex();
        return initMutex;
    }

public:
    static std::atomic<Config*> instancePtr;
    static std::mutex init_mutex;// = new std::mutex();
    ~Config()
    {
    }

    static Config &instance()
    {
        static std::once_flag onceFlag;
        static std::mutex mutex_;
        std::call_once(onceFlag, []() {
            std::lock_guard<std::mutex> lock(mutex_);
            });
        return *instancePtr;
    }

};

错误:

Exception thrown at 0x00007FFC8E2D32A8 (msvcp140.dll) (in MainProcess.exe): 0xC0000005: An access violation occurred while reading location 0x0000000000000000. There is an unhandled exception at 0x00007FFC8E2D32A8 (msvcp140.dll) (in MainProcess.exe): 0xC0000005: An access violation occurred while reading location 0x0000000000000000.

#include <mutex>

void lock() {
        if (_Mtx_lock(_Mymtx()) != _Thrd_result::_Success) {
            // undefined behavior, only occurs for plain mutexes (N4950 [thread.mutex.requirements.mutex.general]/6)
            _STD _Throw_Cpp_error(_RESOURCE_DEADLOCK_WOULD_OCCUR);
        }

出现问题时程序可能崩溃的原因的解决方法: 1.多线程环境下,静态局部变量的初始化不是原子的 2.Release模式下的编译器优化可能会改变代码执行的顺序 3.返回引用可以在对象构造之前使用

如何修改上面的代码来实现我想要的功能

qt5
1个回答
0
投票

1.您可以将 _DISABLE_CONSTEXPR_MUTEX_CONSTRUCTOR 定义为逃生舱口。

2.或者更新msvcp140.dll

参考: https://developercommunity.visualstudio.com/t/Visual-Studio-17100-Update-leads-to-Pr/10669759?sort=newest

© www.soinside.com 2019 - 2024. All rights reserved.