Moving std::thread
Asked Answered
G

2

13

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!

Gerlachovka answered 16/7, 2013 at 10:28 Comment(0)
R
17

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

threadFoo = std::move(threadBar);
Rawden answered 16/7, 2013 at 10:29 Comment(2)
Thank you for an answer. Do I get it right that the one (and the only?) way the expected operator could be used is with a temporary thread object like threadFoo = std::thread(threadFunction);?Gerlachovka
Either a temporary or an unnamed reference as you get from std::move.Rawden
B
2

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

std::thread threadFoo;
std::thread threadBar = std::thread(threadFunction);
threadBar.swap(threadFoo);
Bullard answered 24/4, 2018 at 14:20 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.