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

标签 c++ multithreading sockets c++11 stdthread

我正在尝试实现一个 API,让用户可以并行创建两个通信 channel 。一个 channel 使用 TCP,另一个使用 UDP。我有两个类代表两个 channel 。这些类实现了不同的功能。我希望两个 channel 的功能并行运行。为此,我使用 std::thread 创建两个线程,一个用于每个 channel (类)。 思路如下 头文件看起来像

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

class Channel_2
{
public:
    int anotherfunc(int a, int b);
};

在主cpp文件中 包含头文件

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

  std::thread t(ch1.myfunc, a,b);
  return 0;
}

我收到错误消息,指出构造函数 std::thread 的实例不存在。

我有以下问题。

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

最佳答案

你实际上有两个问题:

  1. 语法错误。您需要传递一个指向成员函数的指针,如

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

    std::thread t(&Channel_1::myfunc, ch1, a, b);
    

关于c++ - 使用 std::thread 从 C++11 中的两个类调用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53282876/

相关文章:

java - 意外的线程行为。能见度

python - 当一个线程正在运行时阻塞其他线程

Java通过Socket发送文件

.net - 安全套接字连接的最佳实践

c++ - 为 ubuntu 写一个 cygwin makefile

c++ - 嵌套枚举类型的后缀增量重载

java - 线程中出现异常 "Thread-***"java.lang.NullPointerException

c# - 与经典 TCP 套接字通信

Windows 的 C++ 事件跟踪 (ETW) 包装器

c++ - 在 C++ 中给出指针常量 View 的更好方法