使用C++的基本线程

Basic Threads using C++

本文关键字:线程 C++ 使用      更新时间:2023-10-16

我正在尝试使用c++创建一个简单的线程。我收到错误:Error 14 error C2276: '&' : illegal operation on bound member function expression

这是我的代码:

void PeerCommunication(PeerData &peerData, std::string infoHash)
{
    Peer peer(peerData.GetIP(), peerData.GetPort(), infoHash);
    peer.CreateConnection();
    peer.HasPeace(0);
    peer.RecievePeace(0, 4056211 + 291); 
}
TcpPeers(OrderedMap<std::string, unsigned short> peers, std::string infoHash, Bencoding bencoder)
{
    std::vector<std::thread> threads;
    //std::thread ttt[num_threads];
    //std::thread t1(task1, "Hello");
    for (std::size_t i = 0; i < peers.GetSize(); i++)
    {
        PeerData pd(peers.GetKeyByIndex(i), peers.GetValueByIndex(i));
        std::thread t(&PeerCommunication, pd, infoHash);
        threads.push_back(t);
    }
    for (std::size_t i = 0; i < peers.GetSize(); i++)
    {
        threads.at(i).join();
    }
    ...
  }

我已经尝试删除引用:std::thread t(PeerCommunication, pd, infoHash);,但它仍然不起作用。

当我这样做(删除引用)时,错误是:Error 4 error C3867: 'TcpPeers::PeerCommunication': function call missing argument list; use '&TcpPeers::PeerCommunication' to create a pointer to member

您需要从PeerCommunication()函数返回一些内容。

我怀疑你想要更像这样的东西:

for (std::size_t i = 0; i < peers.GetSize(); i++)
{
    PeerData pd(peers.GetKeyByIndex(i), peers.GetValueByIndex(i));
    // Use emplace as std::thread non-copyable
    // Pass this pointer with member functions
    // Use std::ref to pass references
    threads.emplace_back(&TcpPeers::PeerCommunication, this, std::ref(pd), infoHash);
}
for (std::size_t i = 0; i < peers.GetSize(); i++)
{
    threads.at(i).join();
}