15 Multithreading the needle – Threads and Concurrency

 

This chapter covers

  • Learning how to create and manage threads
  • Understanding to synchronize threads using mutexes and conditional variables
  • Exploring the concept of atomic types and operations to prevent race conditions
  • Learning how to perform asynchronous programming using promises and futures
  • Exploring the concept of coroutines and how to create lightweight threads

Multithreading is a powerful programming technique, that allows multiple tasks to run simultaneously within a single program. This approach can significantly enhance program performance, by enabling various tasks to execute concurrently.

Throughout this challenging chapter, we will delve into the fundamental concepts of multithreading in C++. We'll begin by exploring how to create and manage threads, which are the building blocks of concurrent execution. We'll then delve into the world of mutexes and thread safety, crucial components for preventing race conditions and ensuring data integrity. Our journey continues with an in-depth look at conditional variables and atomic types and operations, essential tools for synchronization and efficient thread communication.

As we progress, we'll also touch on the concept of asynchronous programming and coroutines - advanced techniques that allow us to write code that executes concurrently without sacrificing readability and maintainability.

15.1 Multithreading – The multitask code

15.1.1 A thread of thought: threads management in C++

15.1.2 The good, the bad and the multithread

15.1.3 Mutex – The tamer of unruly threads

15.1.4 The ABBA pattern (not the Swedish-pop-phenomenal kind)

15.1.5 It’s the integer that counts - Integer operations and threads

15.1.6 Some new multithreading classes

15.2 Asynchronous programming

15.2.1 The promised land: std::future and std::promise

15.2.2 The async Function

15.2.3 Coroutines: Let’s play!

15.3 Summary