c++ - Abort() 已被调用 - Connect Function multithreads Cpp

标签 c++ multithreading sockets thread-safety bittorrent

我正在尝试使用多线程同时连接多个对等点。 当我运行我的代码并运行多个线程时,程序在“connect”函数中崩溃并写道:“Abort() 已被调用”。

这是我调用线程的方式:

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

peer 是我在尝试实现 bittorent 协议(protocol)时需要连接的另一个客户端。

同样,当有一个线程时一切正常,当我有两个以上的对等点时所有崩溃。

最佳答案

当一个 std::thread 对象被销毁时,它不允许是 joinable(),即,在它被销毁之前必须发生以下两种情况之一:

  1. 它被分离了,线程已经失去控制,几乎无法控制它是否完成。
  2. 线程已被join()ed。

如果 std::thread 对象在没有这些状态的情况下被销毁,则调用 std::terminate() 这可能是调用 abort() 你观察到。在您的循环中,您不断销毁线程,而没有对它们调用 detach()join()。系统将其视为终止程序的请求。

如果您需要此行为的引用:请参阅 30.3.1.3 [thread.thread.destr] 第 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 ]

关于c++ - Abort() 已被调用 - Connect Function multithreads Cpp,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34330576/

相关文章:

linux - 写入关闭的 TCP/IP 连接挂起

sockets - 为什么telnet仅在Enter上发送数据?

c++ - 动态检查使用可变参数继承的类的类型的最佳方法是什么?

C++:以最简单和最干净的方式将值写入文件?

Java 不使用所有可用的 CPU

C++ 11 unordered_map 段错误

linux - 为什么 gethostbyname 和 gethostbyaddr 被认为已过时?

c++ - 错误 : undefined reference to `sqlite3_open'

c++ - C++ |使用lambda函数检查流是否成功打开

ios - SKaction 阻止了 touchesBegan 事件