【问题标题】:C++ Calling member function in boost threadC++ 在 boost 线程中调用成员函数
【发布时间】:2013-06-13 02:08:21
【问题描述】:

所以我想在 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。但我无法弄清楚正确的语法是什么。

【问题讨论】:

标签: c++ boost-thread


【解决方案1】:

handle_thread 是一个成员函数,必须这样调用:

int MyClass::Open(){
    boost::thread t(&MyClass::handle_thread, this);
    ...
}

请注意,如果您在之后立即join线程,您的函数将被阻塞。除了handle_thread 实际上在不同的线程上运行之外,该行为将与单线程应用程序的行为相同。但是不会有线程交错(即没有并行性)。

【讨论】:

  • 我怎样才能让我的函数Open 在我启动线程后继续运行?
  • @tzippy std::thread是可移动的。您可以从Open 返回线程对象并在外部进行连接。根据线程的性质,分离线程并返回std::future(类似于std::async 所做的)可能是有意义的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-09-27
  • 2015-11-14
  • 2011-10-06
  • 1970-01-01
  • 2011-04-02
相关资源
最近更新 更多