Topic created by static object deleted before DTor?

My code has the following classes. In other words, there is a static object (singleletone) that creates a stream in CTor, and when its DTor is called, it does some work in the context of this stream (DTor poses some tasks for the stream).

The problem I am facing is that when DTor of B is called, there are no other threads in this process - it seems that this thread is killed by cleaning the process before calling the class B destructor.

Does anyone know why this is happening? and how to avoid it?

UPD: Problems only arise when creating Singleton from a DLL. Everything works fine when Singleton is created from the same executable.

I am using VS2017

Singleton.dll (Ah + A.cpp) Ah --> #pragma once #include <thread> class __declspec(dllexport) A { public: static A* instance(); A(); ~A(); private: bool stopFlag; std::thread mThread; }; A.cpp #include "stdafx.h" #include <thread> #include "Ah" using namespace std; A::A() { mThread = std::thread([this] { while (stopFlag == false) { } }); } A::~A() { stopFlag = true; mThread.join(); } A* A::instance() { static A self; return &self; } 

==================================================== ================================
An executable file that uses the main.cpp DLL

 #include "stdafx.h" #include "Ah" int main() { auto a = A::instance(); return 0; } 

Updated using compiled code. Now, if you compile the first two files as a DLL, and then set a breakpoint in the destructor, you will see that the stream with the lambda function does not exist ....

UPDATE: found answer from myslef. On Windows, a static object from a DLL is unloaded to the last point when all threads are already cleaned up https://msdn.microsoft.com/en-us/library/windows/desktop/dn633971(v=vs.85).aspx

+7
c ++ multithreading destructor std singleton
source share
1 answer

Found myslef answer. On Windows, a static object from a DLL is unloaded to the last point when all threads are already cleaned up https://msdn.microsoft.com/en-us/library/windows/desktop/dn633971(v=vs.85).aspx

+4
source share

All Articles