Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Moving std::thread

Trying the make simple piece of code work:

std::thread threadFoo;

std::thread&& threadBar = std::thread(threadFunction);

threadFoo = threadBar; // thread& operator=( thread&& other ); expected to be called

Getting an error:

use of deleted function 'std::thread& std::thread::operator=(const std::thread&)'

I explicitly define threadBar as an rvalue reference, not a ordinary one. Why is not expected operator being called? How do I move one thread to another?

Thank you!

like image 552
Kolyunya Avatar asked Jul 16 '13 10:07

Kolyunya


2 Answers

Named references are lvalues. Lvalues don't bind to rvalue references. You need to use std::move.

threadFoo = std::move(threadBar);
like image 76
R. Martinho Fernandes Avatar answered Oct 07 '22 18:10

R. Martinho Fernandes


See also std::thread::swap. This could be implemented as

std::thread threadFoo;
std::thread threadBar = std::thread(threadFunction);
threadBar.swap(threadFoo);
like image 25
Jamie Cruickshank Avatar answered Oct 07 '22 17:10

Jamie Cruickshank