我将有问题的代码减少到以下内容。我有一个在自己的线程上运行成员函数的 C 类。在 CI 的析构函数中想要干净地退出这个线程。只要 c 在 main (1) 中定义,这就可以正常工作,但当它是全局变量 (2) 时就不行。在后一种情况下,我看到线程函数返回但 t.join() 挂起。
#include <mutex>
#include <condition_variable>
#include <thread>
#include <iostream>
using namespace std;
class C
{
public:
    C()
    {
        stop = false;
        t = thread(&C::ThreadFunc, this);
    }
    ~C()
    {
        stop = true;
        cv.notify_all();
        if (t.joinable())
        {
            cout << "joining" << endl;
            t.join();
            cout << "joined" << endl;
        }
    }
private:
    void ThreadFunc()
    {
        while (true)
        {
            unique_lock<mutex> lock(m);
            cv.wait(lock, [&]{return stop;});
            cout << "returning" << endl;
            return;
        }
    }
    thread t;
    mutex m;
    condition_variable cv;
    bool stop;
};
C c;  // does *not* work (2)
int _tmain(int argc, _TCHAR* argv[])
{
    C c;  // does work (1)
    return 0;
}
我使用全局变量的原因是它实际上是 dll 的一部分。当在 DLL_PROCESS_DETACH 上从 DllMain 触发析构函数时,会出现同样的问题。这个问题有解释和解决方案吗?