Book Image

Expert C++ - Second Edition

By : Marcelo Guerra Hahn, Araks Tigranyan, John Asatryan, Vardan Grigoryan, Shunguang Wu
5 (1)
Book Image

Expert C++ - Second Edition

5 (1)
By: Marcelo Guerra Hahn, Araks Tigranyan, John Asatryan, Vardan Grigoryan, Shunguang Wu

Overview of this book

Are you an experienced C++ developer eager to take your skills to the next level? This updated edition of Expert C++ is tailored to propel you toward your goals. This book takes you on a journey of building C++ applications while exploring advanced techniques beyond object-oriented programming. Along the way, you'll get to grips with designing templates, including template metaprogramming, and delve into memory management and smart pointers. Once you have a solid grasp of these foundational concepts, you'll advance to more advanced topics such as data structures with STL containers and explore advanced data structures with C++. Additionally, the book covers essential aspects like functional programming, concurrency, and multithreading, and designing concurrent data structures. It also offers insights into designing world-ready applications, incorporating design patterns, and addressing networking and security concerns. Finally, it adds to your knowledge of debugging and testing and large-scale application design. With Expert C++ as your guide, you'll be empowered to push the boundaries of your C++ expertise and unlock new possibilities in software development.
Table of Contents (24 chapters)
1
Part 1:Under the Hood of C++ Programming
7
Part 2: Designing Robust and Efficient Applications
18
Part 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 with 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 declaring and starting a thread using std::thread, which is defined as follows:

#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()
{
    auto ix...