Abort() has been called - Connect Function multithreads Cpp

user3421416 picture user3421416 · Dec 17, 2015 · Viewed 7.1k times · Source

I am trying to use multithread for connecting for more then one peer simultinaly. While I am running my code and run more then a one thread the program crashes in the "connect" function and it writes: "Abort() has been called".

This is How I call to the threads:

TcpPeers(OrderedMap<std::string, unsigned short> peers, std::string     infoHash)
   {
    this->peers = peers;
    peersArr = new Peer[peers.GetSize()];

    for (int i = 0; i < peers.GetSize(); i++)
    {
        Peer * pp = new Peer(peers.GetKeyByIndex(i), peers.GetValueByIndex(i), infoHash);
        *(peersArr + i) = *pp;
    }

    for (int i = 0; i < peers.GetSize(); i++)
    {
        std::thread t1(&Peer::CreateConnection, *(peersArr + i));
    }
}

A peer is another client that I need to connect with while I am trying to implement the bittorent protocol.

Again, when there is one thread all goes right, when I have more then two peers all crashes.

Answer

Dietmar K&#252;hl picture Dietmar Kühl · Dec 17, 2015

When a std::thread object gets destroyed it is not allowed to be joinable(), i.e., one of two things have to happen before it is destroyed:

  1. It was detached and the thread has gone into the wild and there is pretty much no control over whether it has finished or not.
  2. The thread has been join()ed.

If a std::thread object is destroyed without either of these states, std::terminate() is called which is probably the cause for the call to abort() you observe. In your loop you keep destroying threads without having called either detach() or join() on them. The system sees that as a request to terminate your program.

In case you need a reference for this behavior: see 30.3.1.3 [thread.thread.destr] paragraph 1:

~thread();

If joinable(), calls std::terminate(). Otherwise, has no effects. [ Note: Either implicitly detaching or joining a joinable() thread in its destructor could result in difficult to debug correctness (for detach) or performance (for join) bugs encountered only when an exception is raised. Thus the programmer must ensure that the destructor is never executed while the thread is still joinable. —end note ]