c++ - 如何在线程c ++中将自定义类作为参数传递
问题描述
我正在用 C++ 编写服务器,需要将 Connection 类传递给线程,以便线程可以进行处理。但是当我尝试时,它给出了这个错误。
Connection.cpp:12:15: error: no matching constructor for initialization of
'std::thread'
std::thread newThread(threadFunc,this);
^ ~~~~~~~~~~~~~~~
/Library/Developer/CommandLineTools/usr/bin/../include/c++/v1/thread:340:9: note:
candidate constructor template not viable: requires single argument '__f',
but 2 arguments were provided
thread::thread(_Fp __f)
^
/Library/Developer/CommandLineTools/usr/bin/../include/c++/v1/thread:220:5: note:
candidate constructor not viable: requires 1 argument, but 2 were provided
thread(const thread&);
^
/Library/Developer/CommandLineTools/usr/bin/../include/c++/v1/thread:227:5: note:
candidate constructor not viable: requires 0 arguments, but 2 were
provided
thread() _NOEXCEPT : __t_(_LIBCPP_NULL_THREAD) {}
^
1 error generated.
我已经尝试查找它,但它一直说只是使用std::thread(func,parameter)
但它不起作用,正如您在此处看到的那样。
这是我的来源:
连接.cpp
#include "Connection.h"
void threadFunc(Connection c) {
}
Connection::Connection(sockaddr_in addr,uint32_t addrLen, uint32_t fd) {
socketAddr = addr;
socketAddrLength = addrLen;
socketFD = fd;
char buffer[2048] = {0};
std::thread newThread(threadFunc,this);
while(true) {
if (recv(socketFD, buffer, sizeof(buffer), 0 ) > 0) {
ConnectionDefinition def(socketAddr);
printf("%s says: %s", def.toString().c_str(),buffer);
}
bzero(buffer,sizeof(char)*2048);
}
}
Connection::~Connection() {
close(socketFD);
printf("Server closed connection to client\n");
}
连接.h
#pragma once
#include "include.h"
class Connection {
private:
sockaddr_in socketAddr;
uint32_t socketAddrLength;
uint32_t socketFD;
public:
Connection(sockaddr_in addr,uint32_t addrLen, uint32_t fd);
~Connection();
};
我已包含在 include.h 中,所以这不是问题
包括.h
#pragma once
#include <iostream>
#include <cstdint>
#include <sys/socket.h>
#include <netinet/in.h>
#include <unistd.h>
#include <vector>
#include <thread>
#include "utils.h"
#include "Connection.h"
解决方案
类型不匹配
这是因为this
是一个类型的指针,Connection*
而您正试图将它传递给一个接受Connection
. 看起来您的意图实际上是传递一个指向 的指针,threadFunc
如下所示:
void threadFunc(Connection* c) { ... }
现在您可以将其传递this
给可变参数构造函数,std::thread
它应该可以正常工作。
如果它仍然不起作用,您可以尝试以下选项:
可变参数构造函数std::thread
从我个人的经验来看,可变参数构造函数std::thread
有点挑剔并且不会给出好的错误,因此在创建线程时使用 lambda 绑定参数可能更简单:
std::thread newThread([this] { threadFunc(this); });
这可能会被编译器内联,并且也不会造成性能损失。
推荐阅读
- php - 调用函数时 mpdf() 库不起作用
- javascript - 我必须使用多个字段组合对 JavaScript 数组进行排序,其中一个字段是数字和字符串的组合
- flask - Flask app - 如何显示从应用程序内生成的图像?
- tensorflow - TensorFlow 操作似乎不使用 GPU
- css - 带有链接和目标的 CSS 横幅滑块
- php - 如何获取文件夹中的文件数?
- database - MongoDB 指南针未初始化
- laravel - 创建一个 websocket 系统供第三方用户连接
- java - 如何使用 JNA 导入依赖于 Java 中其他 dll 的 dll
- visual-studio-2019 - Visual Studio 2019 没有向我展示 .NET Standard 2.1 和 .NET Core 3.1 作为 Target Framework 的一部分。.NET Core 3.1 安装在我的系统上