首页 > 解决方案 > 如何在线程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"

标签: c++multithreadingnetwork-programming

解决方案


类型不匹配

这是因为this是一个类型的指针,Connection*而您正试图将它传递给一个接受Connection. 看起来您的意图实际上是传递一个指向 的指针threadFunc如下所示:

void threadFunc(Connection* c) { ... }

现在您可以将其传递this给可变参数构造函数,std::thread它应该可以正常工作。

如果它仍然不起作用,您可以尝试以下选项:

可变参数构造函数std::thread

从我个人的经验来看,可变参数构造函数std::thread有点挑剔并且不会给出好的错误,因此在创建线程时使用 lambda 绑定参数可能更简单:

std::thread newThread([this] { threadFunc(this); });

这可能会被编译器内联,并且也不会造成性能损失。


推荐阅读