Book Image

Expert C++

By : Vardan Grigoryan, Shunguang Wu
Book Image

Expert C++

By: Vardan Grigoryan, Shunguang Wu

Overview of this book

C++ has evolved over the years and the latest release – C++20 – is now available. Since C++11, C++ has been constantly enhancing the language feature set. With the new version, you’ll explore an array of features such as concepts, modules, ranges, and coroutines. This book will be your guide to learning the intricacies of the language, techniques, C++ tools, and the new features introduced in C++20, while also helping you apply these when building modern and resilient software. You’ll start by exploring the latest features of C++, and then move on to advanced techniques such as multithreading, concurrency, debugging, monitoring, and high-performance programming. The book will delve into object-oriented programming principles and the C++ Standard Template Library, and even show you how to create custom templates. After this, you’ll learn about different approaches such as test-driven development (TDD), behavior-driven development (BDD), and domain-driven design (DDD), before taking a look at the coding best practices and design patterns essential for building professional-grade applications. Toward the end of the book, you will gain useful insights into the recent C++ advancements in AI and machine learning. By the end of this C++ programming book, you’ll have gained expertise in real-world application development, including the process of designing complex software.
Table of Contents (22 chapters)
1
Section 1: Under the Hood of C++ Programming
7
Section 2: Designing Robust and Efficient Applications
17
Section 3: C++ in the AI World

Working with threads

When the C++ program starts, that is, the main() function starts its execution, you can create and launch new threads that will run concurrently to the main thread. To start a thread in C++, you should declare a thread object and pass it the function that you want to run concurrently to the main thread. The following code demonstrates the declaration and starting of a thread using std::thread defined in <thread>:

#include <thread>
#include <iostream>

void foo() { std::cout << "Testing a thread in C++" << std::endl; }

int main()
{
std::thread test_thread{foo};
}

That's it. We can create a better example to show how two threads work concurrently. Let's say we print numbers in a loop concurrently to see which thread prints what:

#include <thread>
#include <iostream>

void print_numbers_in_background()
{
...