Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::unique_lock<std::mutex> prohibit dll unloading

Tags:

c++

windows

dll

I have an issue while unloading a dll. It is like this one but quit different. I'm loading a dll using LoadLibraryA then call a function and close the dll with FreeLibrary. However, the dll is not unloaded but FreeLibrary return success. reduced code:

void foo() {
    std::unique_lock<std::mutex> lock(mtx_);
}

While debugging the code and looking into Process Explorer unique_lock creates a second thread, but why? Also this thread is running as long as the application runs. There is nothing else; no other handle to the dll, no other functions. Also the dll is still loaded in the program. If I remove the line above, everything is fine. The dll is unloaded fine, no extra threads. So my question is, how to avoid this behavior and why is unique_lock creating a thread?

The mutex is intended for multithreading, but while testing, there is only one thread, loading the dll calling foo, and unloading the dll.

edit:

I don't know if this is a bug in the visual studio implementation of mutex/unique_lock but I solved the problem by using boost's mutex/unique_lock.

like image 709
user1810087 Avatar asked Jan 10 '23 14:01

user1810087


2 Answers

This is a bug in Visual Studio, they increase the reference count of the DLL abnormally when you use std::thread or std::mutex, etc.

See this bug report.

like image 76
Terry Avatar answered Jan 17 '23 17:01

Terry


It looks like this bug has been fixed in Visual Studio 2015. See this for details.

... I can confirm that the issue is not occurring with VS2015. ...

like image 32
sergej Avatar answered Jan 17 '23 17:01

sergej