使用C++的基本线程
Basic Threads using C++
我正在尝试使用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();
}
相关文章:
- 从不同线程使用int64的不同字节安全吗
- 删除一个线程上有数百万个字符串的大型哈希映射会影响另一个线程的性能
- 在C++中使用cURL和多线程
- 为什么我的C#代码在调用回C++COM直到Task时会暂停.等待/线程.加入
- 在cuda线程之间共享大量常量数据
- 如何将元素添加到数组的线程安全函数?
- 线程,如果else语句,都是错误的上下文切换后,会发生什么
- C++Boost Asio Pool线程,带有lambda函数和传递引用变量
- Qt C++静态thread_local QNetworkAccessManager是线程应用程序的好选择吗
- 异常属于C++中的线程还是进程
- C++中的线程安全删除
- C++使用params创建线程函数会导致转换错误
- 类与私有变量的其他类之间的线程安全性
- CoInitialize()在单独的线程上崩溃而不返回
- c++中的线程池
- 线程之间的布尔停止信号
- 为什么std::async使用同一个线程运行函数
- 用于矢量处理的多个线程
- C++为线程工作动态地分割例程
- 为什么我不能在 while 循环中创建线程?