qt5

use mutex, mvsc2017 build, in release mode, the mutex will cause the program to crash


I use the qt5 development environment, use mutex, mvsc2017 build, I don't crash the program in debug mode, but in release mode, the mutex will cause the program to crash

#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;
    }

};

error: 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);
        }

Workarounds for the reasons why the program may crash if something goes wrong: 1.In a multithreaded environment, the initialization of static local variables is not atomic 2.Compiler optimizations in Release mode may change the order in which code is executed 3.The return reference may be used before the object is constructed

How to modify the above code to implement the function I want


Solution

    1. You can define _DISABLE_CONSTEXPR_MUTEX_CONSTRUCTOR as an escape hatch.

    2. Or update the msvcp140.dll

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