Creating a boost::thread with boost::bind() or without

deinocheirus picture deinocheirus · Dec 6, 2012 · Viewed 26.6k times · Source

Some people seem to launch boost::threads using the boost::bind() function, like in the accepted answer of the following question:

Using boost thread and a non-static class function

Whereas other people don't use it at all, like in the answer with the most upvotes of this question:

Best way to start a thread as a member of a C++ class?

So, what's the difference, if it exists?

Answer

goji picture goji · Dec 6, 2012

As you can see by the code below that compile and gives the expected output, boost::bind is completely unnecessary for using boost::thread with free functions, member functions and static member functions:

#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();
}

Output:

hello from free function
hello from static member function
hello from member function

The internal bind in the constructor does all the work for you.

Just added a few extra comments on what happens with each function type. (Hopefully I've read the source correctly!) As far as I can see, using boost::bind externally will not cause it to also double up and be called internally as it will pass through as is.