所以我想在boost线程中启动成员函数Open()
:
.hpp
Class MyClass{
public:
int Open();
private:
void handle_thread();
};
.cpp
int MyClass::Open(){
boost::thread t(handle_thread);
t.join();
return 0;
}
void MyClass::handle_thread(){
//do stuff
}
test.cpp
int main(){
MyClass* testObject = new MyClass()
testObject.Open();
}
这会导致编译器错误。
error: no matching function for call to 'boost::thread::thread(<unresolved overloaded function type>)'
我看到 Open() 不知道在哪个对象上调用 handle_thread。但我不知道正确的语法是什么。
最佳答案
handle_thread
是一个成员函数,必须这样调用:
int MyClass::Open(){
boost::thread t(&MyClass::handle_thread, this);
...
}
请注意,如果您随后立即加入
线程,您的函数将被阻塞。除了 handle_thread
实际上在不同的线程上运行之外,该行为与单线程应用程序的行为相同。但是不会有线程交错(即没有并行性)。
关于C++在boost线程中调用成员函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17142136/