Thread created by static object deleted before DTor?

I have the following classes in my code. In other words, There is a static object (singletone) which creates thread in CTor, and when its DTor is called, it has some work to be done in the context of this thread (DTor puts some jobs for the thread).

The problem that i face is that when the DTor of B is called there are no other threads running in the process - seems like this thread is killed by process cleanup before calling the destructor of class B.

Anyone knows why this happens? and how to avoid it?

UPD: The problems occures only when Singleton is created from DLL. All works fine when Singleton is created from the same executable.

I am using VS2017

  Singleton.dll (A.h + A.cpp)

A.h --> 

#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 "A.h"

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

================================================================================
Executable which uses DLL main.cpp

#include "stdafx.h"
#include "A.h"


int main()
{
    auto a = A::instance();
    return 0;
}

Updated with the compilable code. Now if you compile the first two files as DLL, and then put breakpoint in A's destructor, you will see that thread with lambda function does not exists....

UPDATE: Found an answer by myslef. In Windows, static object from DLL are unloaded ay very last point when all threads are already cleaned up https://msdn.microsoft.com/en-us/library/windows/desktop/dn633971(v=vs.85).aspx


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

链接地址: http://www.djcxy.com/p/95820.html

上一篇: Eclipse无法在Web页面编辑器中打开.vue文件

下一篇: 在DTor之前删除静态对象创建的线程?