Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a performance cost using std::move vs using a pointer to the thread?

I imagine std::move() has a bit more of a performance cost in the context of something like:

std::thread thrd(&func, this);
someArrOfThreads[0] = std::move(thrd);

vs

std::thread *thrd = new std::thread(&func, this);
someArrOfThreadPointers[0] = thrd;

Is this true? And if so, is it a matter of std::move() changes the boundaries of memory of the thread or something else?

I realize there is the difference that in the first I am actually assigning a value of the array to the thread, and the other being the pointer to the thread, the thread stays in its address(es) in the second.

like image 506
Christian Grabowski Avatar asked Oct 17 '16 23:10

Christian Grabowski


2 Answers

The only thing that std::move does is turn a lvalue into an rvalue reference. This then causes the rvalue reference version of the assignment operator to be called. From a code generation point of view it is a noop.

The rvalue overload is likely to be more efficient since it is allowed to move class internal as opposed to performing a deep copy.

like image 99
doron Avatar answered Nov 15 '22 07:11

doron


How threads are implemented is very platform specific. However classes that implement move semantics typically hold only a handle for or pointer to the actual objects they manage.

For that reason the std::move is likely to be doing something similar to your pointer example on the inside. You can generally expect moving objects to be efficient.

Looking at how std::thread is implemented in GCC on Linux it apparently contains one data item a solitary unsigned long int which is the handle to a thread using the <pthreads> library.

When you do someArrOfThreads[0] = std::move(thrd); it simply swaps the thread's handle with the one in the array.

That should be pretty fast and you don't have the constant overhead of using indirection that you would have if you were using pointers.

Even though implementations may differ the std::move version using values rather than the pointer has to be preferred.

Typically move semantics are as fast as (and possibly faster than) using pointers but also they are generally safer and less fiddly.

like image 31
Galik Avatar answered Nov 15 '22 07:11

Galik