Search icon CANCEL
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Concurrency with Modern C++

You're reading from   Concurrency with Modern C++ What every professional C++ programmer should know about concurrency.

Arrow left icon
Product type Paperback
Published in Dec 2019
Publisher
ISBN-13 9781839211027
Length 543 pages
Edition 1st Edition
Languages
Arrow right icon
Author (1):
Arrow left icon
Rainer Grimm Rainer Grimm
Author Profile Icon Rainer Grimm
Rainer Grimm
Arrow right icon
View More author details
Toc

Table of Contents (19) Chapters Close

1. Reader Testimonials FREE CHAPTER
2. Introduction 3. Concurrency with Modern C++ 4. Memory Model 5. Multithreading 6. Parallel Algorithms of the Standard Template Library 7. The Near Future: C++20 8. Case Studies 9. The Future: C++23 10. Patterns and Best Practices 11. Synchronisation Patterns 12. Concurrent Architecture 13. Best Practices 14. Lock-Based Data Structures 15. Challenges 16. The Time Library 17. CppMem - An Overview 18. Glossary 19. Index

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.

Erronous moving 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...

lock icon The rest of the chapter is locked
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at AU $24.99/month. Cancel anytime