The following code leads into an increasing usage of memory:
#include <shared_mutex>
class foo
{
public:
void bar()
{
std::unique_lock lock(m_mtx);
}
std::shared_mutex m_mtx;
};
int main()
{
while (1)
{
foo obj;
obj.bar();
}
}
The following do not: (only changes the mutex type)
#include <mutex>
class foo
{
public:
void bar()
{
std::unique_lock lock(m_mtx);
}
std::mutex m_mtx;
};
int main()
{
while (1)
{
foo obj;
obj.bar();
}
}
I am using Windows 7 and using the task manager to track the memory consumption of my program.
I compile with mingw and this simple command line to compile:
g++.exe -std=c++17 -o mytest main.cpp
What i am doing wrong with the usage of shared_mutex ?
Found it! Quite an old post, don't known if it's still relevant for you.
The problem seems to be using g++, mingw64 and the std::shared_mutex (at least version 12-posix).
In fact, there is a memory leak in the C++ library using the standard header file, <shared_mutex>. The pthread_rwlock_destroy is not called when PTHREAD_RWLOCK_INITIALIZER is used to initialize the mutex. However, pthread_rwlock_destroy is called as expected when using the pthread_rwlock_init version.
I found a way around and a fix. The easy way is to "disable" the constant initializer PTHREAD_RWLOCK_INITIALIZER from your source code; this forces the C++ library to call the pthread_rwlock_init function, then the pthread_rwlock_destroy function. To do that, just insert an #undef between #include <pthread> and #include <mutex>:
#include <thread>
#undef PTHREAD_RWLOCK_INITIALIZER
#include <mutex>
#include <shared_mutex>
The proper way is to patch the <shared_mutex> header file of the C++ standard library and call the pthread_rwlock_destroy function in the shared_mutex destructor, even if the constant initializer PTHREAD_RWLOCK_INITIALIZER is used.
If I find the way to and the time, I will submit a regular patch for the standard <shared_mutex> header file.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With