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.
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:
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()
, callsstd::terminate()
. Otherwise, has no effects. [ Note: Either implicitly detaching or joining ajoinable()
thread in its destructor could result in difficult to debug correctness (fordetach
) or performance (forjoin
) bugs encountered only when an exception is raised. Thus the programmer must ensure that the destructor is never executed while the thread is stilljoinable
. —end note ]