使用std :: thread从C++ 11中的两个类调用函数

D_w*_*der 0 c++ sockets multithreading c++11 stdthread

我正在尝试实现一个API,让用户可以并行创建两个通信通道.一个通道使用TCP,另一个使用UDP.我有两个代表两个频道的课程.这些类实现了不同的功能.我希望两个通道的功能并行运行.为此,我std::thread用来创建两个线程,每个通道一个(类).想法是以下以下头文件的样子

class Channel_1
{
public:
     int myfunc(int a, int b);
};

class Channel_2
{
public:
    int anotherfunc(int a, int b);
};
Run Code Online (Sandbox Code Playgroud)

在主cpp文件中包含头文件

int main()
{
  int a = 10, b = 20;
  Channel_1 ch1;
  Channel_2 ch2;

  std::thread t(ch1.myfunc, a,b);
  return 0;
}
Run Code Online (Sandbox Code Playgroud)

我得到错误说没有构造函数的实例std::thread存在.

我有以下问题.

  1. 我们不能从线程构造函数中的类调用函数吗?
  2. 使用线程来调用来自不同类的函数的想法是否有意义?

Som*_*ude 6

你实际上有两个问题:

  1. 语法错误.您需要将指针传递给成员函数,如

    std::thread t(&Channel_1::myfunc, a, b);
    
    Run Code Online (Sandbox Code Playgroud)
  2. 需要在类的实例上调用非静态成员函数.必须将此实例作为第一个参数传递:

    std::thread t(&Channel_1::myfunc, ch1, a, b);
    
    Run Code Online (Sandbox Code Playgroud)