0

I've read a lot about this, but I haven't found any solution yet.

My problem is that when I try to do this, I loose control.

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

I'm working with a class implementing the singleton pattern in a multithread environment. My project is compiled to a DLL library. Everything works fine except thread creation.

I've tried this (link) and this example works fine in a stand alone console app, but my project is running as a DLL library.

When I load it from other C++ and C# projects it works fine, and when calling other methods it works well too. The problem occurs whe I call std::thread.

Here is the most important pieces of my code:

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

Any idea why it does not work?

Felix Glas
  • 15,065
  • 7
  • 53
  • 82
jromeror
  • 100
  • 12

1 Answers1

2

I think it has to do with the fact that you try to create the thread from DllMain, see also:

Creating a thread in DllMain?

Community
  • 1
  • 1
Martijn Wijns
  • 501
  • 7
  • 19
  • Thanks very mucha. Yes, I call to PlayerClientSingleton::instance()->initialize(); from DLL_PROCESS_ATTACH, but, It's what I expected to do. I'm looking for an alternative... but not easy... – jromeror Jun 03 '14 at 10:50
  • I would suggest calling PlayerClientSingleton::initialize explicitly from the code using your dll. – Martijn Wijns Jun 03 '14 at 10:55
  • Yesss thanks. I made an Init function for call from the code that use dll. But now I've a new question... before that, I destroyed the singleton instance from DllMain too, but now, I must do it explictly too? – jromeror Jun 03 '14 at 11:12
  • Thanks very much, now It works fine, without your support, never be the solution I would have thought. I've not reputation for voteUp you, but I am tremendously grateful to you. – jromeror Jun 03 '14 at 11:42
  • I'm glad it works. Can you accept the answer to make clear that this question is answered? – Martijn Wijns Jun 03 '14 at 12:14