C++在boost线程中调用成员函数

标签 c++ boost-thread

所以我想在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/

相关文章:

c# - 在没有枚举的情况下在 C# 中实现自己的数据类型?

c++ fstream更改文件中的空间

c++ - 如何在代码中使用eclipse项目变量

c++ - 更好地理解 boost 的聊天客户端示例

C++ boost 线程 : Passing a method of an object

c++ - 总线错误 10 - char * array

c++ - 为什么带有 const 参数的函数声明允许调用带有非常量参数的函数?

c++ - 程序.exe : Native' has exited with code 255 (0xff)

c++ - 使用 boost::thread::interrupt() 时,您*需要*捕获 thread_interrupted 异常吗?

c++ - 从 std::thread 在主线程上执行回调函数