Search code examples
c++c++11stdbind

std::bind a thread memeber variable to an instance of a class


I am confused between the various ways I can create member threads to run on member functions of a class instance and what are the differences between all of them :- First method - using lambda expressions

auto m_thread = std::thread([this]{run();});

Second method

auto m_thread = std::thread(std::bind(&MyType::run, this));

Third method

auto res = std::bind(&m_thread, std::bind(&MyType::run, this));

Fourth method -

auto res = std::bind(&m_thread, &MyType::run, this);

Here, m_thread is a member variable of a Class MyType given by std::thread m_thread of which this is an instance and run is a member function of the same class. Will all of these give the same results and are they equivalent? Also, in the last two cases how to make the thread start executing.


Solution

  • std::bind expects a callable at first argument (but doesn't reject invalid arguments).

    So 3rd and 4th method create unusable objects.

    To create the std::thread, you have indeed several available variant:

    • std::thread(&MyType::run, this);
    • std::thread(std::bind(&MyType::run, this)); No advantages from above.
    • std::thread([this](){ return this->run(); ); Allows to handle run overloads, default parameters.