c++ - 单例和 .dll 中的 std::thread block

标签 c++ multithreading dll thread-safety stdthread

我已经阅读了很多关于此的内容,但我还没有找到任何解决方案。

我的问题是,当我尝试这样做时,我失去了控制。

hiloEscucha = std::thread(&PlayerClientSingleton::Run, this);

我正在使用一个在多线程环境中实现单例模式的类。我的项目被编译成一个 DLL 库。除了创建线程外,一切正常。

我试过这个 ( link ),这个例子在独立的控制台应用程序中运行良好,但我的项目作为 DLL 库运行。

当我从其他 C++ 和 C# 项目加载它时,它运行良好,并且在调用其他方法时它也运行良好。当我调用 std::thread 时出现问题。

这是我的代码中最重要的部分:

class PlayerClientSingleton : public PlayerClient {
public:
    static PlayerClientSingleton* instance(void) {
        std::call_once(m_onceFlag, [] { m_instance = new PlayerClientSingleton; });
        return m_instance;
    }

    //Initialize is called from the .dll initialization (Dllmain)
    bool initialize(void) { 
        runThread();
    }

    void runThread(void) {
        m_thread = std::thread(&PlayerClientSingleton::Run, this);

        if (m_thread.joinable()) {
            m_thread.detach();
        }
    }

    static PlayerClientSingleton* m_instance;
    static std::once_flag         m_onceFlag;
    std::thread                   m_thread;
}

class PlayerClient {
protected:
    virtual void Run() {
        while (!m_threadEdn) {
            doSomething();
        }
    }
}

知道为什么它不起作用吗?

最佳答案

我认为这与您尝试从 DllMain 创建线程这一事实有关,另请参阅:

Creating a thread in DllMain?

关于c++ - 单例和 .dll 中的 std::thread block ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24012776/

相关文章:

java - 为什么在 jUnit 测试中非守护线程会终止?

c# - Java .NET 互操作

c++ - 程序崩溃时 C++ ofstream 的行为

C++ 逻辑错误 [N-Queen]

c++ - 使用信号量并调用 wait() 和 signal()

android - 为什么这个线程不会暂停和循环?

c++ - 在基于范围的 for 循环中使用 shared_ptr 到 std::vector

c++ - 您可以在 C++ 中制作自定义运算符吗?

c++ - 用静态库构建共享库

python - Python 包装器中的 Fortran DLL,相同功能的输出不同