Moving Threads
Moving threads make the lifetime issues of threads even harder.
A thread supports the move semantic but not the copy semantic. The reason being the copy constructor of std::thread is set to delete: thread(const thread&) = delete;. Imagine what happens if you copy a thread while the thread is holding a lock.
Let’s move a thread.
1 // threadMoved.cpp
2
3 #include <iostream>
4 #include <thread>
5 #include <utility>
6
7 int main(){
8
9 std::thread t([]{std::cout << std::this_thread::get_id();});
10 std::thread t2([]{std::cout << std::this_thread::get_id();});
11
12 t = std::move(t2);
13 t.join();
14 t2.join();
15
16 }
Both threads t and t2 should do their simple job: printing their IDs. In addition to that, thread t2 is moved to t (line 12). In the end, the main thread takes care of its children and joins them. But wait, the result is very different from my expectations...