Book Image

Advanced C++

By : Gazihan Alankus, Olena Lizina, Rakesh Mane, Vivek Nagarajan, Brian Price
5 (1)
Book Image

Advanced C++

5 (1)
By: Gazihan Alankus, Olena Lizina, Rakesh Mane, Vivek Nagarajan, Brian Price

Overview of this book

C++ is one of the most widely used programming languages and is applied in a variety of domains, right from gaming to graphical user interface (GUI) programming and even operating systems. If you're looking to expand your career opportunities, mastering the advanced features of C++ is key. The book begins with advanced C++ concepts by helping you decipher the sophisticated C++ type system and understand how various stages of compilation convert source code to object code. You'll then learn how to recognize the tools that need to be used in order to control the flow of execution, capture data, and pass data around. By creating small models, you'll even discover how to use advanced lambdas and captures and express common API design patterns in C++. As you cover later chapters, you'll explore ways to optimize your code by learning about memory alignment, cache access, and the time a program takes to run. The concluding chapter will help you to maximize performance by understanding modern CPU branch prediction and how to make your code cache-friendly. By the end of this book, you'll have developed programming skills that will set you apart from other C++ programmers.
Table of Contents (11 chapters)
7
6. Streams and I/O

Review Synchronization, Data Hazards, and Race Conditions

The key challenge of multithreaded programming is knowing how the threads work with shared data. Shared data, also known as resources, are not only variables, but also file descriptors and environment variables, and even Windows registries. For example, if the threads just read the data, then there are no problems and no synchronization is required. However, if at least one of the threads edits the data, race conditions could arise. Usually, the operations on the data are not atomic, that is, they require several steps. Even the simplest increment operation of a numeric variable is performed in the following three steps:

  1. Read the value of the variable.
  2. Increment it.
  3. Write the new value.

Due to the OSes interruptions, the thread can be stopped before it completes the operation. For example, we have threads A and B and have a variable that is equal to 0.

Thread A starts the increment:

  1. Reads the value of the variable...