Dries
Dries

Reputation: 1005

Starting thread causing abort()

I'm trying to create a thread with the regular c++11 threads. I have an object called NetworkManager that creates a thread of one of its methods in its constructor like this:

void NetworkManager()
{
    // Raknet setup here...
    std::thread networkUpdate(&NetworkManager::update, this);

    // Set timers
    playerDataTimer.start();
    playerDataTimer.pause();

    Logger::log("NetworkManager constructor ended");
}

The update method handles the messages coming on from other clients via the RakNet library like here: Link

I did the same thing as in the example where it's encapsulated in a while loop that keeps going forever.

When I try to create this thread in the constructor however I get an abort() message (the application crashes) and I can't figure out why this is. All objects that are used in the thread are setup before the loop starts so I don't think that's the issue.

Upvotes: 2

Views: 3307

Answers (2)

Mat
Mat

Reputation: 206689

The std::thread object you're creating gets destroyed at the end of your constructor since it is a local variable. If the destructor of a std::thread is called while the thread is joinable (like it is in your example), std::terminate is called.

You must keep that thread object as a member of your class, or store it somewhere else, or detach the thread. (Or join with it in your constructor, but that doesn't sound like it would do what you want.)

Upvotes: 4

typ1232
typ1232

Reputation: 5607

Your app terminates because the std::thread is destructed without being .detached or .joined.

~thread();
Destroys the thread object.
If *this has an associated thread (joinable() == true), std::terminate() is called.

Upvotes: 1

Related Questions