使用boost :: bind()或不使用boost :: bind创建boost :: thread

dei*_*rus 11 c++ boost boost-thread

有些人似乎使用boost :: bind()函数启动boost :: threads,就像在以下问题的接受答案中一样:

使用boost线程和非静态类函数

而其他人完全没有使用它,就像这个问题最赞成的回答一样:

将线程作为C++类的成员启动的最佳方法是什么?

那么,如果它存在,有什么区别?

goj*_*oji 13

正如你在下面的代码中看到的那样编译并给出了预期的输出,对于使用带有自由函数,成员函数和静态成员函数的boost :: thread来说,完全不需要boost :: bind:

#include <boost/thread/thread.hpp>
#include <iostream>

void FreeFunction()
{
  std::cout << "hello from free function" << std::endl;
}

struct SomeClass
{
  void MemberFunction()
  {
    std::cout << "hello from member function" << std::endl;
  }

  static void StaticFunction()
  {
    std::cout << "hello from static member function" << std::endl;
  }
};

int main()
{
  SomeClass someClass;

  // this free function will be used internally as is
  boost::thread t1(&FreeFunction);
  t1.join();

  // this static member function will be used internally as is
  boost::thread t2(&SomeClass::StaticFunction);
  t2.join();

  // boost::bind will be called on this member function internally
  boost::thread t3(&SomeClass::MemberFunction, someClass);
  t3.join();
}
Run Code Online (Sandbox Code Playgroud)

输出:

hello from free function
hello from static member function
hello from member function
Run Code Online (Sandbox Code Playgroud)

构造函数中的内部绑定可以为您完成所有工作.

只是添加了一些关于每种功能类型会发生什么的额外评论.(希望我已经正确阅读了源代码!)据我所知,在外部使用boost :: bind不会导致它加倍并在内部调用,因为它将按原样通过.

  • 人们可能会使用`boost :: bind`,因为他们不知道`boost :: thread`的内部绑定 (3认同)

Igo*_* R. 10

没有区别 - thread构造函数在bind内部使用.人们bind明确地使用历史原因,因为Boost.Thread 在1.36之前没有"绑定"构造函数.