Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does std::thread take function to run by rvalue?

There is one thing about std::thread which I don't understand: why the constructor of std::thread takes function to run by rvalue?

I usually want to run a Functor with some members to another thread. Like this:

struct Function
{
    void operator() ( /* some args */)
    {
        /* some code */
    }

    /* some members */
}


void run_thread()
{
    Functor f( /* some data */);
    std::thread thread(f, /* some data */);

    /* do something and wait for thread to finish */
}

With current implementation of std::thread I must be sure my object is implementing move semantics. I don't get why cannot I pass it by reference.

Extra question is: what does it mean to refer to function by rvalue? Lambda expression?

like image 432
Michał Walenciak Avatar asked Jun 23 '15 21:06

Michał Walenciak


1 Answers

In your run_thread method f is an auto variable. That means at the bottom of the scope f will be destroyed. You claim that you will "wait for the thread to finish" but the compiler/runtime system does not know that! It has to assume that f will be deleted, possibly before the thread that is supposed to call its method has a chance to start.

By copying (or moving) the f, the run time system gains control of the lifetime of its copy of f and can avoid some really nasty, hard to debug problems.

like image 152
Dale Wilson Avatar answered Sep 30 '22 06:09

Dale Wilson