Search code examples
c++multithreadingc++11boost-thread

Arguments in std::thread. How works?


Examples of use std::thread constructor:

#include <thread>
using namespace std;

void a_function(){}
void a_function2(int a){}
void a_function3(int a,int b){}
void a_function4(int &a){}

class a_class
{
public:
    void a_function5(int a){}
};

int main()
{
    a_class aux;
    int a = 2;

    thread t(a_function);
    thread t2(a_function2,2);
    thread t3(a_function3,2,3);
    thread t4(a_function4,ref(a));
    thread t5(&a_class::a_function5,&aux,2);

    t.join();
    t2.join();
    t3.join();
    t4.join();
    t5.join();
}

How can constructor knows number of arguments? How can constructor calls one unknown type of function? How could i implement something like that? By example, one wrapper for std::thread

class wrapper_thread
{
   thread t;

   public:

         wrapper_thread() //what arguments here?
         : t() //What arguments here?
         {}
}

Solution

  • What you're looking for is the parameter pack operator. Using this it's possible to write a function that accepts a variable number of arguments. It can do things with those arguments, such as forward them to another function.

    Keep in mind that because templates are instantiated at compile time, the number of arguments and their types must be known at the call site.

    A simple way to implement your wrapper thread class' constructor might be:

    template <typename ... Args> // this ctor has variadic template arguments
    wrapper_thread(Args& ... args) // pack references to arguments into 'args' 
         : t(args...) //unpack arguments, pass them as parameters to the ctor of std::thread
    

    Once you've got your head around that, you can look at std::forward() to do perfect forwarding. Andrei Alexandrescu gives a great talk on variadic templates. You can find it here: http://channel9.msdn.com/Events/GoingNative/GoingNative-2012/Variadic-Templates-are-Funadic