Search code examples
c++c++11stdthread

can not understand std::thread usage


I am reading documents about c++11 multi-threads, and met this example for std::thread.

Code:

void thread_task(int n) {
  ...
}

int main(int argc, const char *argv[])
{
    std::thread threads[5];
    for (int i = 0; i < 5; i++) {
        threads[i] = std::thread(thread_task, i + 1);
    }

    return 0;
}

I do not understand threads[i] = std::thread(thread_task, i + 1);. Is the std::thread a static function call, and returns a reference for std::thread object? Sounds inconceivable, but seems to be what the code say.

Because I would write it like this:

std::thread *threads[5];
for (int i = 0; i < 5; i++) {
    threads[i] = new std::thread(thread_task, i + 1);
}

Thanks.


Solution

  • Let's go through exactly what is happening:

    std::thread threads[5];
    

    This creates an array of 5 std::thread objects, which are default constructed. Currently they represent "not a thread" as this is the state default construction leaves them in.

    for (int i = 0; i < 5; i++) {
        threads[i] = std::thread(thread_task, i + 1);
    }
    

    This uses the move form of operator=. Because threads are not copyable, only moveable, thread& operator=(thread&& t) is defined while thread& operator=(const thread& t) is not. This assigns the thread object in threads[i] to the newly constructed std::thread(thread_task, i + 1);.

    There is no reason to use an array of pointers here. It adds nothing but the possibility for memory leaks.