std::mutex lock hangs when overriding the new operator

若如初见. 提交于 2019-12-03 16:08:27

The mutex library uses new, and std::mutex is not recursive (i.e. reentrant) by default. A chicken-and-egg problem.

UPDATE As has been pointed out in the comments below, using std::recursive_mutex may work. But the classic C++ problem of the order of static initialization of globals being not well defined remains, as does the danger of outside access to the global mutex (best to put it inside an anonymous namespace.)

UPDATE 2 You may be switching g_systemInitiated to true too early, i.e. before the mutex has had a chance to complete its initialization, and so the "first-time-through" call to malloc() never happens. To force this, you could try replacing the assignment in main() with a call to an initialization function in the allocator module:

namespace {
    std::recursive_mutex    g_mutex;
    bool                    g_initialized = false;
}
void initialize()
{
    g_mutex.lock();
    g_initialized = true;
    g_mutex.unlock();
}

All of your examples are broken, except the first one, which is just very bad practice for not using a scoped lock type.

This should work, if it doesn't your compiler or standard library is broken:

#include <mutex>

std::mutex g_mutex;

void *operator new(size_t size)
{
   std::lock_guard<std::mutex> lock(g_mutex);
   ...   
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!