mardi 29 septembre 2015

std::thread as member of class executing random thread causing an abort at asignate thread

In my class I have thread object as public membe:

class AppManager{
   ...
    public:
    std::thread m_thread;
};

Then when I initialize the thread:

void* BridgeFunction(void *pctx) {
    ((AppManager*)pctx)->MainAppThread();
    return 0;
}

void AppManager::CreateAppThread(){
   m_thread = std::thread(&BridgeFunction, this);
   m_thread.detach();
}

I got an Abort on std::terminate:

 thread& operator=(thread&& __t) noexcept
    {
      if (joinable())
      std::terminate();
      swap(__t);
      return *this;
    }

Why? I'm calling detach, I tried changing from:

m_thread = std::thread(&BridgeFunction, this);

To:

m_thread = std::thread(&AppManager::MainAppThread, this);

And the same, it works only if I declare the m_thread as global and I debugged why it works, turns out that the thread declared as member execute a random thread before I assign the thread, I know this because I printed the id to see if it was joinable:

    auto myid = m_thread.get_id();
    std::stringstream ss;
    ss << myid;
    std::string thread_id = ss.str();

    LogPrintDebug("[Thread Activity] -  Id of thread not created yet: %s", thread_id.c_str());

    m_thread = std::thread(&BridgeFunction, this);
    m_thread.detach();

It prints:

[Thread Activity] - Id of thread not created yet: 1074643408

When I declare global the thread it prints:

[Thread Activity] - Id of thread not created yet::id of a non-executing thread

I printed also the Id of my actual thread and it's different than the Id of the random thread, so try to terminate it due to the part:

if (joinable())
 std::terminate();

I'm using Visual Studio 2015 running an Android Native Activity using Clang 3.6 and the GNU STL libraries, ndk r10e.

I tested the same code on windows and the id of the thread is 0, doesn't get any Abort.

Thanks

Aucun commentaire:

Enregistrer un commentaire