代码:
// create class instance
MC_THREAD MTHR;
// set some values in the class
MTHR.setup_mc_thread("com6", &es);
// create an thread to run the non-static member function
std::thread MCTHR(MC_THREAD::start_mc_thread, std::ref(MTHR));
函数的定义是:
void MC_THREAD::start_mc_thread(){
while(1){
//do_stuff
}
}
以上代码使用基于 gcc 5.1.0 的 TDM-GCC 编译器在 Windows 8 和 10 上编译(并正常工作)。
上面的代码在 linux 上使用 gcc 7.3.1 生成以下错误:
错误:无效使用非静态成员函数‘void MC_THREAD::start_mc_thread()’|
产生错误的机器正在运行 fedora 27 using gcc (GCC) 7.3.1 20180303 (Red Hat 7.3.1-5)
如有任何建议,我们将不胜感激!
已解决:请参阅下方 Sam 的评论
还必须链接 pthread。
最佳答案
我最初认为问题出在 std::reference_wrapper
的使用上。但是编译错误实际上是由于类成员函数需要是一个指针。以下使用 gcc 7.3.1 编译:
#include <thread>
#include <utility>
#include <functional>
class x {
public:
void start_thread();
};
int main()
{
x y;
std::thread thr{&x::start_thread, std::ref(y)};
}
为类成员启动线程的常用方法是传递一个普通指针作为类实例。这也适用,在这种情况下:
std::thread thr{&x::start_thread, &y};
这是更常见的语法。引用包装器并不是真正需要的。但在所有情况下,第一个参数必须是指向类方法的指针。 &x::start_thread
就是这样一个指针。 x::start_thread
本身不是。这才是真正的问题。
std::thread
构造函数的参数 is specified merely as...
f - Callable object to execute in the new thread
你必须真正深入研究the definition of a callable object .我想到的基本用法对应于此处列出的可调用对象的第三个选项。但是引用包装器也是可以接受的。但是,在所有情况下,您都必须将指向成员函数的指针作为第一个参数。
关于C++11 线程 - 非静态成员函数的无效使用 - 工作 gcc 5.1.0 损坏的 gcc 7.3.1,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49685127/