我正在尝试实现一个 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
的实例不存在。
我有以下问题。
- 我们不能在线程中调用类中的函数吗 构造函数?
- 这种使用线程来调用来自不同类的函数的想法是否有意义?
最佳答案
你实际上有两个问题:
语法错误。您需要传递一个指向成员函数的指针,如
std::thread t(&Channel_1::myfunc, a, b);
非静态成员函数需要在类的实例上调用。此实例必须作为第一个参数传递:
std::thread t(&Channel_1::myfunc, ch1, a, b);
关于c++ - 使用 std::thread 从 C++11 中的两个类调用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53282876/