<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Shreyos Ghosh</title>
    <description>The latest articles on DEV Community by Shreyos Ghosh (@shreyosghosh).</description>
    <link>https://dev.to/shreyosghosh</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F956212%2F938a8ab7-ddab-4eed-8074-01aaa1fbe9aa.jpeg</url>
      <title>DEV Community: Shreyos Ghosh</title>
      <link>https://dev.to/shreyosghosh</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/shreyosghosh"/>
    <language>en</language>
    <item>
      <title>Behind the Scenes of C++ | Compiling and Linking</title>
      <dc:creator>Shreyos Ghosh</dc:creator>
      <pubDate>Fri, 27 Oct 2023 13:49:30 +0000</pubDate>
      <link>https://dev.to/shreyosghosh/behind-the-scenes-of-c-compiling-and-linking-j0n</link>
      <guid>https://dev.to/shreyosghosh/behind-the-scenes-of-c-compiling-and-linking-j0n</guid>
      <description>&lt;p&gt;&lt;strong&gt;C++&lt;/strong&gt; is a compiled language, which means that in order to run a program, one must convert it to machine-level language. While most of us use an IDE(Integrated Development Environment) which makes it for all intents and purposes, as easy as clicking a button. Which means most of the process is just abstracted away from us.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fo94syiepni3t01ol8zpm.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fo94syiepni3t01ol8zpm.png" alt="Text to Binary Convertion"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;In this blog post, we'll deeply analyze the inner steps and processes which need to be done to convert our text-based code to machine-understandable form.&lt;/p&gt;

&lt;p&gt;Grab your coffee...and write your &lt;code&gt;helloworld.cpp&lt;/code&gt; program we're going to convert it to &lt;code&gt;helloworld.exe&lt;/code&gt; soon...&lt;/p&gt;

&lt;h2&gt;
  
  
  Hello World of C++
&lt;/h2&gt;

&lt;p&gt;Let's write our first C++ program. Open a text file in notepad or any text editor of your choice and simply paste or type the below C++ code. And save it as &lt;code&gt;helloworld.cpp&lt;/code&gt;.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight cpp"&gt;&lt;code&gt;

&lt;span class="c1"&gt;// This is our simple hello world program&lt;/span&gt;
&lt;span class="cp"&gt;#include&lt;/span&gt; &lt;span class="cpf"&gt;&amp;lt;iostream&amp;gt;&lt;/span&gt;&lt;span class="cp"&gt;
&lt;/span&gt;
&lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="nf"&gt;main&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="n"&gt;argc&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="kt"&gt;char&lt;/span&gt;&lt;span class="o"&gt;*&lt;/span&gt; &lt;span class="n"&gt;argv&lt;/span&gt;&lt;span class="p"&gt;[])&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="c1"&gt;// this line below will print "Hello World!" to the screen&lt;/span&gt;
    &lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;cout&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&amp;lt;&lt;/span&gt; &lt;span class="s"&gt;"Hello World!"&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&amp;lt;&lt;/span&gt; &lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;endl&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;cin&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;get&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;
    &lt;span class="c1"&gt;// if all goes well the main will return 0&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Here, we will use a compiler provided by GNU called &lt;code&gt;g++&lt;/code&gt; to convert our C++ code to executable binary.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Note:&lt;/strong&gt; C++ compilers doesn't have any way to tell whether you've written a &lt;strong&gt;C++&lt;/strong&gt; code or any other code in the file, other than to look on the file extension in this case &lt;code&gt;.cpp&lt;/code&gt;. So, if you're writing a C++ source code you must save it using the extension &lt;code&gt;.cpp&lt;/code&gt; or &lt;code&gt;.c++&lt;/code&gt;, &lt;code&gt;.cxx&lt;/code&gt;, &lt;code&gt;.cp&lt;/code&gt;, &lt;code&gt;.C&lt;/code&gt;. Now, for header files there is no such restrictions from the compiler itself. But, it is a best practice to name the header file with &lt;code&gt;.h&lt;/code&gt; or &lt;code&gt;.hpp&lt;/code&gt; extensions to maintain the code clarity and consistency.&lt;/p&gt;

&lt;p&gt;Don't worry if you find the above code ambiguous, We'll talk more about the code in detail and also about headers(why we use headers and how actually it works) in my upcoming blogs.&lt;/p&gt;

&lt;p&gt;Once you have your &lt;code&gt;helloworld.cpp&lt;/code&gt; file, open the command prompt and navigate to the folder where you've saved your &lt;code&gt;helloworld.cpp&lt;/code&gt; program. And run the command below to get the output file &lt;code&gt;helloworld.exe&lt;/code&gt;.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

g++ helloworld.cpp -o helloworld.exe


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;Note:&lt;/strong&gt; If you're on Windows, to use the &lt;code&gt;g++&lt;/code&gt; compiler you must install the GNU toolchain port on Windows also known as MinGW-w64(Minimalist GNU for Windows) in your system.&lt;/p&gt;

&lt;p&gt;By, now you should have the &lt;code&gt;helloworld.exe&lt;/code&gt; file, upon clicking on it you'll have the "Hello World!" printed on your terminal window.&lt;/p&gt;

&lt;p&gt;So, let's have a look on how the compiler converts our C++ code into machine executable form.&lt;/p&gt;

&lt;h2&gt;
  
  
  The C++ Compilation Model
&lt;/h2&gt;

&lt;p&gt;To convert our C++ code into executable binary, the C++ compilers use the compilation model. It consists of a few essential stages that lay the foundation for successful code execution.&lt;/p&gt;

&lt;p&gt;These stages consists of,&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;&lt;em&gt;Preprocessing&lt;/em&gt;&lt;/strong&gt; of the source code&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;&lt;em&gt;Compiling&lt;/em&gt;&lt;/strong&gt; the processed source code&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;&lt;em&gt;Assembling&lt;/em&gt;&lt;/strong&gt; the compiled file&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;&lt;em&gt;Linking&lt;/em&gt;&lt;/strong&gt; the object code binary&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Ffcau1e7v5n5l1to0ykfq.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Ffcau1e7v5n5l1to0ykfq.png" alt="The C++ Compilation Model"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Let's talk about these stages into a bit more detailed way.&lt;/p&gt;

&lt;h3&gt;
  
  
  Preprocessing:
&lt;/h3&gt;

&lt;p&gt;This is the first stage in the build process where the source codes undergoes a series of text formatting before the actual compilation begins. Which are,&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Handling Preprocessor Directives:&lt;/strong&gt; Preprocessor Directives or Preprocessor Statements are the commands that starts with the &lt;strong&gt;'#'&lt;/strong&gt; symbol, and it instruct the preprocessor to perform certain textual manipulation on the source code. Which can be further categorized by,&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;em&gt;File Inclusion Directive&lt;/em&gt; - Embeds the contents of library headers and source headers to the source code. (Basically a simple copy and paste) Example: &lt;code&gt;#include&lt;/code&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;em&gt;Macro Definition Directive&lt;/em&gt; - Replaces identifiers with replacement tokens or token-strings in the current file. Example: &lt;code&gt;#define&lt;/code&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;em&gt;Conditional Directives&lt;/em&gt; - Conditionally compile sections of the current file. Example: &lt;code&gt;#if&lt;/code&gt;, &lt;code&gt;#endif&lt;/code&gt;, &lt;code&gt;#ifdef&lt;/code&gt;, &lt;code&gt;#ifndef&lt;/code&gt;, &lt;code&gt;#else&lt;/code&gt;, &lt;code&gt;#elif&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;
&lt;em&gt;Pragma Directives&lt;/em&gt; - Applies compiler-specific rules to specified sections of code. Example: &lt;code&gt;#pragma once&lt;/code&gt;.&lt;/li&gt;
&lt;/ul&gt;


&lt;/li&gt;

&lt;li&gt;&lt;p&gt;&lt;strong&gt;Removal of the Comments:&lt;/strong&gt; Having the ability to write comments is a remarkable feature in C++. Making it more versatile and readable for us human readers. &lt;br&gt;&lt;br&gt;
&lt;strong&gt;Note:&lt;/strong&gt; In, C++ we can write comments using two forward-slash &lt;strong&gt;"//Text-Comment"&lt;/strong&gt;(Single-Line) or like this &lt;strong&gt;"/*Text-Comment*/"&lt;/strong&gt;(Multi-Line). &lt;br&gt;&lt;br&gt;
However, the comments have no utility for the machine since the English language grammar is "far too loosely structured" to be used in the later stages. This is why during the preprocessing stage all the comments mentioned in the source file are replaced with one space character each and the newline characters are retained.&lt;/p&gt;&lt;/li&gt;

&lt;/ul&gt;

&lt;p&gt;To, generate a preprocessed file &lt;code&gt;helloworld.i&lt;/code&gt; from the &lt;code&gt;helloworld.cpp&lt;/code&gt; source code, navigate to the source code directory again and run the below command,&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

g++ -E helloworld.cpp -o helloworld.i


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Now, If you take a look at the generated preprocessed file, you'll see that, it is no longer our small helloworld program, rather it contains thousands of lines of code.&lt;/p&gt;

&lt;p&gt;This is an indication that the preprocessor has done its job. It copied and pasted all the contents from the library header file &lt;code&gt;iostream&lt;/code&gt; into the top of our &lt;code&gt;helloworld.cpp&lt;/code&gt; file. And at the very end of the file content, you should see that all the comments are removed from our helloworld program.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

# 3 "helloworld.cpp" 2


# 4 "helloworld.cpp"
int main(int argc, char* argv[]) {

    std::cout &amp;lt;&amp;lt; "Hello World!" &amp;lt;&amp;lt; std::endl;
    std::cin.get();

    return 0;
}


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;h3&gt;
  
  
  Compiling:
&lt;/h3&gt;

&lt;p&gt;After the preprocessing of the source code is done, the individual intermediate source files are fed into the compiler as a separate translation unit where these files confront a series of phases to be transformed into assembler files.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fq3sox4wazhuqu4bkjhib.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fq3sox4wazhuqu4bkjhib.png" alt="Translation Units"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;These phases includes,&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fibhtsyexk23rjld91adw.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fibhtsyexk23rjld91adw.png" alt="Phases of a Compiler"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Lexical Analysis or Tokenization:&lt;/strong&gt; In this phase, the source code lexemes(sequence of characters) are categorized into tokens. For example let's see how the compiler will tokenize the following line of preprocessed source code.&lt;/li&gt;
&lt;/ul&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight cpp"&gt;&lt;code&gt;

&lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="nf"&gt;main&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Lexemes&lt;/th&gt;
&lt;th&gt;Tokens&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;int&lt;/td&gt;
&lt;td&gt;Keyword&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;main&lt;/td&gt;
&lt;td&gt;Identifier&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;(&lt;/td&gt;
&lt;td&gt;Left parenthesis(Operator)&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;)&lt;/td&gt;
&lt;td&gt;Right parenthesis(Operator)&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;{&lt;/td&gt;
&lt;td&gt;Left curly brace(Punctuator)&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;return&lt;/td&gt;
&lt;td&gt;Keyword&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;0&lt;/td&gt;
&lt;td&gt;Integer literal&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;;&lt;/td&gt;
&lt;td&gt;Semicolon(Punctuator)&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;}&lt;/td&gt;
&lt;td&gt;Right curly brace(Punctuator)&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;Note:&lt;/strong&gt; &lt;strong&gt;Tokens&lt;/strong&gt; are the smallest individual units of a program. C++ has different types of tokens, some of which are &lt;strong&gt;keyword&lt;/strong&gt;(&lt;code&gt;if&lt;/code&gt;, &lt;code&gt;return&lt;/code&gt;, &lt;code&gt;int&lt;/code&gt;), &lt;strong&gt;identifier&lt;/strong&gt;(&lt;code&gt;main&lt;/code&gt;, &lt;code&gt;foo&lt;/code&gt;, &lt;code&gt;var&lt;/code&gt;), &lt;strong&gt;literal&lt;/strong&gt;(&lt;code&gt;3.1415f&lt;/code&gt;, &lt;code&gt;0&lt;/code&gt;, &lt;code&gt;"Hello World!"&lt;/code&gt;), &lt;strong&gt;Operator&lt;/strong&gt;(&lt;code&gt;=&lt;/code&gt;, &lt;code&gt;+&lt;/code&gt;, &lt;code&gt;-&lt;/code&gt;) and &lt;strong&gt;Punctuator&lt;/strong&gt;(&lt;code&gt;(&lt;/code&gt;, &lt;code&gt;)&lt;/code&gt;, &lt;code&gt;{&lt;/code&gt;, &lt;code&gt;}&lt;/code&gt;, &lt;code&gt;;&lt;/code&gt;).&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Syntax Analysis or Parsing:&lt;/strong&gt; During the syntax analysis the tokens are organized into a hierarchical structure known as a parse tree to check if the written code conforms to the language's syntax rules or not.&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight cpp"&gt;&lt;code&gt;

&lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="nf"&gt;main&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="c1"&gt;// The above code will generate error in the syntax analysis.&lt;/span&gt;

&lt;span class="n"&gt;helloworld&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;cpp&lt;/span&gt;&lt;span class="o"&gt;:&lt;/span&gt;&lt;span class="mi"&gt;5&lt;/span&gt;&lt;span class="o"&gt;:&lt;/span&gt;&lt;span class="mi"&gt;13&lt;/span&gt;&lt;span class="o"&gt;:&lt;/span&gt; &lt;span class="n"&gt;error&lt;/span&gt;&lt;span class="o"&gt;:&lt;/span&gt; &lt;span class="n"&gt;expected&lt;/span&gt; &lt;span class="sc"&gt;';'&lt;/span&gt; &lt;span class="n"&gt;before&lt;/span&gt; &lt;span class="sc"&gt;'}'&lt;/span&gt; &lt;span class="n"&gt;token&lt;/span&gt;
    &lt;span class="mi"&gt;5&lt;/span&gt; &lt;span class="o"&gt;|&lt;/span&gt;     &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;
      &lt;span class="o"&gt;|&lt;/span&gt;             &lt;span class="o"&gt;^&lt;/span&gt;


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Semantical Analysis:&lt;/strong&gt; Semantical analysis focuses on checking the code's computational meaning and context. It converts the parse tree generated in the parsing phase, into a simpler abstract form without the unnecessary syntactical details such as braces, and commas, which is also known as Abstract Syntax Tree.&lt;br&gt;
&lt;br&gt;&lt;/p&gt;

&lt;p&gt;With the help of the AST, the parser verifies whether the variables are initialized before being used, whether types are compatible, and whether the code's behaviour aligns with the intended semantics of the language.&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight cpp"&gt;&lt;code&gt;

&lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="n"&gt;var&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="s"&gt;"Hello"&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;  &lt;span class="c1"&gt;// incompatible types 'var'(int) and "Hello"(const char*)&lt;/span&gt;
&lt;span class="n"&gt;pi&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mf"&gt;3.1415&lt;/span&gt;&lt;span class="n"&gt;f&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;       &lt;span class="c1"&gt;// variable 'pi' not declared&lt;/span&gt;
&lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="n"&gt;x&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="n"&gt;result&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;x&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="mi"&gt;3&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt; &lt;span class="c1"&gt;// variable 'x' not initialized&lt;/span&gt;


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Intermediate Code Generation:&lt;/strong&gt; During this phase, the front end tree(AST), which we've obtained from the semantical analysis, is converted into an intermediate representation(&lt;strong&gt;IR&lt;/strong&gt;), before it's sent to the optimizer for further analysis.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Note:&lt;/strong&gt; One of the main reasons for this conversion is, essentially due to the fact that ASTs differ across different languages(C, C++). This means that performing the same type of optimization logic, on each language would require a different implementation. Which is not very ideal to maintain and upgrade.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;g++&lt;/strong&gt; uses a three-address-based IR called &lt;strong&gt;GIMPLE&lt;/strong&gt;(GNU SIMPLE representation) for high-level optimizations which is fully independent of the processor being targeted.&lt;/p&gt;

&lt;p&gt;You can generate the GIMPLE file from the source file &lt;code&gt;helloworld.cpp&lt;/code&gt; directly by using the following command.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

g++ -fdump-tree-gimple=helloworld.gimple helloworld.cpp -o helloworld.exe


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Code Optimization:&lt;/strong&gt; This is the phase, also known as the middle end where most of the optimizations occur. These optimizations are mainly focused on the higher level, meaning that it won't be targeting the final hardware just yet.&lt;br&gt;
&lt;br&gt;&lt;/p&gt;

&lt;p&gt;Instead the optimization strategy is focused on various operations such as dead code elimination, removing redundant calculations, loop optimizations, constant folding, among others.&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight cpp"&gt;&lt;code&gt;

&lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="nf"&gt;foo&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="n"&gt;x&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="n"&gt;y&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="n"&gt;val&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;10&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;5&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt; &lt;span class="mi"&gt;3&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt; &lt;span class="c1"&gt;//&amp;lt;= The value of this expression&lt;/span&gt;
                            &lt;span class="c1"&gt;//   will be replaced with one integer &lt;/span&gt;
                            &lt;span class="c1"&gt;//   literal "25" during compile time &lt;/span&gt;
                            &lt;span class="c1"&gt;//   vs. calculating it in runtime.&lt;/span&gt;
    &lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="n"&gt;sum&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;x&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="n"&gt;y&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;x&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="n"&gt;y&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt; &lt;span class="c1"&gt;//&amp;lt;= Redundant code; This can be removed with&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;                 &lt;span class="c1"&gt;//   the value of "sum" or the previous line can&lt;/span&gt;
                  &lt;span class="c1"&gt;//   be totally removed during the optimization &lt;/span&gt;
                  &lt;span class="c1"&gt;//   phase.&lt;/span&gt;


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Target Code Generation:&lt;/strong&gt; Within this final phase the compiler converts the higher-level IR into a relatively lower-level format called &lt;strong&gt;RTL&lt;/strong&gt;(Register Transfer Language). Which is very similar to assembly instructions but only contains pseudo-registers so that low-level optimizations can be easily performed on it.&lt;br&gt;
&lt;br&gt;&lt;/p&gt;

&lt;p&gt;The RTL is generated to adhere to the target architecture so that the real registers can be replaced with the pseudo registers later on in the register allocation phase. After the register allocation phase, the assembly instruction code is produced as an output string.&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;To generate the assembler source file use the following command,&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

g++ -S helloworld.cpp


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;h3&gt;
  
  
  Assembling:
&lt;/h3&gt;

&lt;p&gt;In, the assembling stage the source assembler file that we have got from the last stage is sent to the assembler, where each of the source program statements are converted into a bit stream to construct the object code binary.&lt;/p&gt;

&lt;p&gt;You can generate the object file &lt;code&gt;helloworld.o&lt;/code&gt; from the &lt;code&gt;helloworld.cpp&lt;/code&gt; file directly by running the command below,&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

g++ -c helloworld.cpp


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;The object code that we get out of this is not usable yet or executable to be exact. This is because we need to link the library code which holds the actual implementation for all the features that we have used in our &lt;code&gt;helloworld&lt;/code&gt; program. This is where we need the linker.&lt;/p&gt;

&lt;h3&gt;
  
  
  Linking:
&lt;/h3&gt;

&lt;p&gt;This is the final stage of the whole C++ compilation model, where the different object files generated from individual source files as a different translation unit get linked with the library files.&lt;/p&gt;

&lt;p&gt;There are two ways to combine or link these two parts,&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Static Linking:&lt;/strong&gt; In, static linking, our separate &lt;code&gt;.obj&lt;/code&gt; files and the static library &lt;code&gt;.lib&lt;/code&gt; file are linked by the linker in the compile time(before the code gets executed in the memory) and produce a single portable executable binary.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fqomk0jd8c0u3o774phfx.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fqomk0jd8c0u3o774phfx.png" alt="Static Linking"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Note:&lt;/strong&gt; You might wonder why we need to link the &lt;code&gt;.lib&lt;/code&gt; file when we've already included the &lt;code&gt;iostream&lt;/code&gt; file. It is because the header files such as &lt;code&gt;iostream&lt;/code&gt; only hold the features (i.e. declarations of variables, function signatures) that are available. However, the actual implementation of those functions can be found in a library file. And by combining those two parts we get a final executable file.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Dynamic Linking:&lt;/strong&gt; Dynamic linking happens when our already compiled executable is linked with the runtime implementation of the library also called dynamically linked library file or &lt;code&gt;.dll&lt;/code&gt; file.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fs54swl3v7fm2tp27gmnw.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fs54swl3v7fm2tp27gmnw.png" alt="Dynamic Linking"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Congrats! I hope you now have a good understanding of how the C++ compilation model and the linker function together to transform our C++ code into machine language.&lt;/p&gt;

&lt;p&gt;Here, are some of the resource links that I read/watched while making this post. I highly encourage reading them if you're willing to learn more,&lt;/p&gt;

&lt;p&gt;C++ Books That I have followed:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Programming: Principles and Practice Using C++ by Bjarne Stroustrup&lt;/li&gt;
&lt;li&gt;C++ Fundamentals by Antonio Mallia and Francesco Zoffoli&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;About-&lt;/p&gt;

&lt;p&gt;Compiling and Linking:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href="https://youtu.be/cpkDQaYttR4?si=DnV715eStRumC7fY" rel="noopener noreferrer"&gt;https://youtu.be/cpkDQaYttR4?si=DnV715eStRumC7fY&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Preprocessor Directives:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href="https://learn.microsoft.com/en-us/cpp/preprocessor/preprocessor-directives?view=msvc-170" rel="noopener noreferrer"&gt;https://learn.microsoft.com/en-us/cpp/preprocessor/preprocessor-directives?view=msvc-170&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://www.ibm.com/docs/en/i/7.1?topic=reference-preprocessor-directives" rel="noopener noreferrer"&gt;https://www.ibm.com/docs/en/i/7.1?topic=reference-preprocessor-directives&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Compiler:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href="https://www.wikiwand.com/en/Compiler" rel="noopener noreferrer"&gt;https://www.wikiwand.com/en/Compiler&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://www.wikiwand.com/en/GNU_Compiler_Collection" rel="noopener noreferrer"&gt;https://www.wikiwand.com/en/GNU_Compiler_Collection&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://en.wikibooks.org/wiki/GNU_C_Compiler_Internals/GNU_C_Compiler_Architecture" rel="noopener noreferrer"&gt;https://en.wikibooks.org/wiki/GNU_C_Compiler_Internals/GNU_C_Compiler_Architecture&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://youtu.be/3tIqpEmWMLI?si=kWXduRVtHH1rT1Vg" rel="noopener noreferrer"&gt;https://youtu.be/3tIqpEmWMLI?si=kWXduRVtHH1rT1Vg&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;GCC Internals:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href="https://www.wikiwand.com/en/GNU_Compiler_Collection" rel="noopener noreferrer"&gt;https://www.wikiwand.com/en/GNU_Compiler_Collection&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://en.wikibooks.org/wiki/GNU_C_Compiler_Internals/GNU_C_Compiler_Architecture" rel="noopener noreferrer"&gt;https://en.wikibooks.org/wiki/GNU_C_Compiler_Internals/GNU_C_Compiler_Architecture&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://youtu.be/OYDocHc8sqc?si=1YCqYA5OF9TDaOlZ" rel="noopener noreferrer"&gt;https://youtu.be/OYDocHc8sqc?si=1YCqYA5OF9TDaOlZ&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Linker:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href="https://youtu.be/H4s55GgAg0I?si=4NkNvXkm4VHcGJ2k" rel="noopener noreferrer"&gt;https://youtu.be/H4s55GgAg0I?si=4NkNvXkm4VHcGJ2k&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

</description>
      <category>cpp</category>
      <category>beginners</category>
      <category>programming</category>
    </item>
    <item>
      <title>Multithreading | Handling Race Conditions and Deadlocks in C++</title>
      <dc:creator>Shreyos Ghosh</dc:creator>
      <pubDate>Fri, 17 Feb 2023 15:54:54 +0000</pubDate>
      <link>https://dev.to/shreyosghosh/multithreading-handling-race-conditions-and-deadlocks-in-c-4ae4</link>
      <guid>https://dev.to/shreyosghosh/multithreading-handling-race-conditions-and-deadlocks-in-c-4ae4</guid>
      <description>&lt;p&gt;Previously, we've seen some different ways to create a thread instance and how to manage them using the &lt;code&gt;join()&lt;/code&gt; and &lt;code&gt;detach()&lt;/code&gt; methods.&lt;/p&gt;

&lt;p&gt;In this article, I will discuss about move semantics of thread ownership, mutexes, and other related topics.&lt;/p&gt;

&lt;h2&gt;
  
  
  Move Ownership of a Thread:
&lt;/h2&gt;

&lt;p&gt;In C++ &lt;code&gt;&amp;lt;thread&amp;gt;&lt;/code&gt; by using &lt;code&gt;std::move&lt;/code&gt; function we can move the ownership of an executable thread between different thread instances/objects.&lt;/p&gt;

&lt;p&gt;As &lt;code&gt;std::thread&lt;/code&gt; is a resource owning type, a thread of execution can only be moved across different instances but not copied to eliminate the chance of resource wastage.&lt;/p&gt;

&lt;p&gt;Okay, enough talking! let's have a look at the example code,&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

1. void my_work();  //callable function
2. void my_other_work();
3. std::thread my_worker1(my_work);  //construction of thread 
   //object specifying the task
4. std::thread my_worker2;  //default constructed thread object
5. my_worker2 = std::move(my_worker1);  //moving ownership of the 
   //executable thread
6. my_worker1 = std::thread(my_other_work);  //construction of 
   //a new thread associated with temporary object


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;&lt;em&gt;&lt;code&gt;Code Example:&lt;/code&gt;&lt;/em&gt;&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight cpp"&gt;&lt;code&gt;

&lt;span class="cp"&gt;#include&lt;/span&gt; &lt;span class="cpf"&gt;&amp;lt;iostream&amp;gt;&lt;/span&gt;&lt;span class="cp"&gt;
#include&lt;/span&gt; &lt;span class="cpf"&gt;&amp;lt;thread&amp;gt;&lt;/span&gt;&lt;span class="cp"&gt;
&lt;/span&gt;
&lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="n"&gt;count&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="kt"&gt;void&lt;/span&gt; &lt;span class="nf"&gt;my_work&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="k"&gt;while&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;count&lt;/span&gt;&lt;span class="o"&gt;++&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&lt;/span&gt; &lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;cout&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&amp;lt;&lt;/span&gt; &lt;span class="s"&gt;"Doing my work!"&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&amp;lt;&lt;/span&gt; &lt;span class="s"&gt;"&lt;/span&gt;&lt;span class="se"&gt;\n&lt;/span&gt;&lt;span class="s"&gt;"&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;
    &lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;cout&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&amp;lt;&lt;/span&gt; &lt;span class="s"&gt;"My work is complete!"&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&amp;lt;&lt;/span&gt; &lt;span class="s"&gt;"&lt;/span&gt;&lt;span class="se"&gt;\n&lt;/span&gt;&lt;span class="s"&gt;"&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="kt"&gt;void&lt;/span&gt; &lt;span class="nf"&gt;my_other_work&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="k"&gt;while&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;count&lt;/span&gt;&lt;span class="o"&gt;++&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&lt;/span&gt; &lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;cout&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&amp;lt;&lt;/span&gt; &lt;span class="s"&gt;"Doing my other work!"&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&amp;lt;&lt;/span&gt; &lt;span class="s"&gt;"&lt;/span&gt;&lt;span class="se"&gt;\n&lt;/span&gt;&lt;span class="s"&gt;"&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;
    &lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;cout&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&amp;lt;&lt;/span&gt; &lt;span class="s"&gt;"My other work is complete!"&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&amp;lt;&lt;/span&gt; &lt;span class="s"&gt;"&lt;/span&gt;&lt;span class="se"&gt;\n&lt;/span&gt;&lt;span class="s"&gt;"&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="nf"&gt;main&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="kr"&gt;thread&lt;/span&gt; &lt;span class="n"&gt;my_worker1&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;my_work&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
    &lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;cout&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&amp;lt;&lt;/span&gt; &lt;span class="s"&gt;"Thread Id of my_worker1 is "&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&amp;lt;&lt;/span&gt; &lt;span class="n"&gt;my_worker1&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;get_id&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&amp;lt;&lt;/span&gt; &lt;span class="s"&gt;"&lt;/span&gt;&lt;span class="se"&gt;\n&lt;/span&gt;&lt;span class="s"&gt;"&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="kr"&gt;thread&lt;/span&gt; &lt;span class="n"&gt;my_worker2&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="n"&gt;my_worker2&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;move&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;my_worker1&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
    &lt;span class="n"&gt;my_worker1&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="kr"&gt;thread&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;my_other_work&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
    &lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;cout&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&amp;lt;&lt;/span&gt; &lt;span class="s"&gt;"Thread Id of my_worker1 is "&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&amp;lt;&lt;/span&gt; &lt;span class="n"&gt;my_worker1&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;get_id&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&amp;lt;&lt;/span&gt; &lt;span class="s"&gt;"&lt;/span&gt;&lt;span class="se"&gt;\n&lt;/span&gt;&lt;span class="s"&gt;"&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;cout&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&amp;lt;&lt;/span&gt; &lt;span class="s"&gt;"Thread Id of my_worker2 is "&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&amp;lt;&lt;/span&gt; &lt;span class="n"&gt;my_worker2&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;get_id&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&amp;lt;&lt;/span&gt; &lt;span class="s"&gt;"&lt;/span&gt;&lt;span class="se"&gt;\n&lt;/span&gt;&lt;span class="s"&gt;"&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="n"&gt;my_worker1&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;join&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;
    &lt;span class="n"&gt;my_worker2&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;join&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;&lt;em&gt;&lt;code&gt;Code Output:&lt;/code&gt;&lt;/em&gt;&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

Thread Id of my_worker1 is 2
Thread Id of my_worker1 is 3
Thread Id of my_worker2 is 2
Doing my work!
My work is complete!
Doing my other work!
My other work is complete!


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;&lt;em&gt;&lt;code&gt;Explanation:&lt;/code&gt;&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;In our above code, at first in &lt;code&gt;main&lt;/code&gt; function we created a new thread &lt;code&gt;my_worker1&lt;/code&gt; using the &lt;code&gt;std::thread&lt;/code&gt; constructor, which is associated with the &lt;code&gt;my_work&lt;/code&gt; function.&lt;/p&gt;

&lt;p&gt;Next, we created a default constructed thread object &lt;code&gt;my_worker2&lt;/code&gt;(i.e. it is not associated with any executable thread). In which we moved the &lt;code&gt;my_worker1&lt;/code&gt; thread object, using &lt;code&gt;std::move&lt;/code&gt; function.&lt;/p&gt;

&lt;p&gt;Doing this transfers the ownership of the underlying thread from &lt;code&gt;my_worker1&lt;/code&gt; to &lt;code&gt;my_worker2&lt;/code&gt;, leaving &lt;code&gt;my_worker1&lt;/code&gt; in an invalid state.&lt;/p&gt;

&lt;p&gt;After this, we have created a new thread that is associated with the &lt;code&gt;std::thread&lt;/code&gt; temporary object and assigned it to the &lt;code&gt;my_worker1&lt;/code&gt; thread object.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight cpp"&gt;&lt;code&gt;

&lt;span class="n"&gt;my_worker1&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="kr"&gt;thread&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;my_other_work&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;blockquote&gt;
&lt;p&gt;When we call &lt;code&gt;std::thread&lt;/code&gt; by only specifying the task, the &lt;code&gt;std::thread&lt;/code&gt; constructor creates a temporary object and assigns the ownership of the newly created thread to that object. Now, this thread doesn't start it's execution immediately. We can start it by providing a thread object to it.&lt;br&gt;
That's why I've used the &lt;strong&gt;move assignment operator&lt;/strong&gt; to assign the returned thread object by the &lt;code&gt;std::thread&lt;/code&gt; constructor, to the thread object &lt;code&gt;my_worker1&lt;/code&gt;. As you can see we don't need to call &lt;code&gt;std::move&lt;/code&gt; for such assignment operations.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Here, I've used the &lt;code&gt;get_id&lt;/code&gt; function to print the underlying thread ID to show that the ownership is actually getting transferred.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Now one thing to note, the thread ID may be different on your system, as it's determined by the OS and can vary from one run to the next. The value of the thread ID is not guaranteed to be unique(i.e. thread ID's can be recycled) or to have any particular meaning. It is simply a numerical identifier that is used to distinguish one thread from another within the same program.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;For some reason, if you don't want to use &lt;code&gt;std::move&lt;/code&gt; function, you can also use &lt;code&gt;std::thread::swap&lt;/code&gt; to swap the ownership of the underlying threads.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

1. thread_name.swap(other_thread_name);
or,
2. std::swap(thread_name, other_thread_name);


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Now, I guess we should move to our next topic.&lt;/p&gt;

&lt;h2&gt;
  
  
  Race Condition and Data Race:
&lt;/h2&gt;

&lt;p&gt;Suppose you're facing such a scenario, where you've more than one concurrent thread, trying to access and modify the same shared data concurrently and depending on the order in which they access the data the final outcome differs. Now, this can cause reliability issues in the program, this is what we call a &lt;strong&gt;Race Condition&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Data Races&lt;/strong&gt; occur when two or more threads access a common memory location simultaneously and at least one of them modifies the data resulting in undefined corrupt data at that memory location.&lt;/p&gt;

&lt;p&gt;It is possible that Race Conditions can occur because of Data Race or vice versa.&lt;/p&gt;

&lt;p&gt;Let's see this with an example.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;&lt;code&gt;Code Example:&lt;/code&gt;&lt;/em&gt;&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight cpp"&gt;&lt;code&gt;

&lt;span class="cp"&gt;#include&lt;/span&gt; &lt;span class="cpf"&gt;&amp;lt;iostream&amp;gt;&lt;/span&gt;&lt;span class="cp"&gt;
#include&lt;/span&gt; &lt;span class="cpf"&gt;&amp;lt;thread&amp;gt;&lt;/span&gt;&lt;span class="cp"&gt;
&lt;/span&gt;
&lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="n"&gt;shared_counter&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="kt"&gt;void&lt;/span&gt; &lt;span class="nf"&gt;increment_counter&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="n"&gt;i&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt; &lt;span class="n"&gt;i&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&lt;/span&gt; &lt;span class="mi"&gt;100000&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt; &lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="o"&gt;++&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="c1"&gt;//--critical region--//&lt;/span&gt;
        &lt;span class="n"&gt;shared_counter&lt;/span&gt;&lt;span class="o"&gt;++&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="nf"&gt;main&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="kr"&gt;thread&lt;/span&gt; &lt;span class="n"&gt;my_worker1&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;increment_counter&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
    &lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="kr"&gt;thread&lt;/span&gt; &lt;span class="n"&gt;my_worker2&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;increment_counter&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;

    &lt;span class="n"&gt;my_worker1&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;join&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;
    &lt;span class="n"&gt;my_worker2&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;join&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;

    &lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;cout&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&amp;lt;&lt;/span&gt; &lt;span class="s"&gt;"Final counter value: "&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&amp;lt;&lt;/span&gt; &lt;span class="n"&gt;shared_counter&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&amp;lt;&lt;/span&gt; &lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;endl&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Before I explain the code, it's important to know that when we call the &lt;code&gt;std::thread&lt;/code&gt; object specifying the task, the C++ threading API uses the lower level API (&lt;strong&gt;&lt;em&gt;Win&lt;/em&gt;&lt;/strong&gt;&lt;strong&gt;API&lt;/strong&gt; for Windows) provided by the OS to launch a thread of execution.&lt;/p&gt;

&lt;p&gt;In the process of which, the OS allocates the associated kernel resources and stack space and then it adds the new thread to the scheduler. After that, the thread scheduler executes those threads depending on it's various algorithms(FCFS, Time Slicing, Priority Based).&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Different OS may use a different approach to schedule the threads. In case of Windows, it follows a priority-driven, preemptive scheduling system. Which means the threads scheduler can interrupt a running thread at any time and yield it's execution by putting it into a wait state to allow another thread with higher priority to execute.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Now that we have a bit of an idea about the underlying details let's get back to the code example.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;&lt;code&gt;Explanation:&lt;/code&gt;&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;So here, we have two concurrent threads &lt;code&gt;my_worker1&lt;/code&gt; and &lt;code&gt;my_worker2&lt;/code&gt; and both of them are working on the same &lt;code&gt;shared_counter&lt;/code&gt; variable and doing increment operations for 100k times each. Cool!&lt;/p&gt;

&lt;p&gt;It would be a fair guess if you think that the output will be 200k. But, after running the code quite a few times the outcome is nowhere near the expected result(At least for me). Now, why is it happening?&lt;/p&gt;

&lt;p&gt;As I previously said, these two threads are running concurrently, so there is a chance that the progress made by one thread can be overridden by another thread because of the asynchronized interleaving instructions and the data race.&lt;/p&gt;

&lt;p&gt;Here is the visualization of what might have happened.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fhqm6pnmj0al3wq2tnvds.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fhqm6pnmj0al3wq2tnvds.gif" alt="Race Condition and Data Race Visualization GIF"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Even though each thread has done the increment operation once but the final value stored in &lt;code&gt;shared_counter&lt;/code&gt; is only 1, which is not the desired output.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Disclaimer:&lt;/strong&gt; This visualization is only one of many scenarios that are possible, which means the order of these threads accessing the &lt;code&gt;shared_counter&lt;/code&gt; variable can change. Now, run the for loop for 200k times and it ends up with complete chaos...&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;As Race Condition depends on the relative ordering of the instructions, most of the time it won't cause any issues(i.e. Benign Race Condition) as long as the invariants are not broken. But a problematic race condition may result in a broken invariant (final value ≠ expected value).&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;So, it is evident that we need some kind of synchronization for our threads. This is where Mutual Exclusion or Mutex come into play!&lt;/p&gt;

&lt;h2&gt;
  
  
  Thread Mutexes:
&lt;/h2&gt;

&lt;p&gt;&lt;code&gt;std::mutex&lt;/code&gt; class is a synchronization primitive that provides a locking mechanism which can be used to protect shared data from being simultaneously accessed by multiple threads.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;&lt;code&gt;Code Example:&lt;/code&gt;&lt;/em&gt;&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight cpp"&gt;&lt;code&gt;

&lt;span class="cp"&gt;#include&lt;/span&gt; &lt;span class="cpf"&gt;&amp;lt;iostream&amp;gt;&lt;/span&gt;&lt;span class="cp"&gt;
#include&lt;/span&gt; &lt;span class="cpf"&gt;&amp;lt;thread&amp;gt;&lt;/span&gt;&lt;span class="cp"&gt;
#include&lt;/span&gt; &lt;span class="cpf"&gt;&amp;lt;mutex&amp;gt;&lt;/span&gt;&lt;span class="cp"&gt;
&lt;/span&gt;
&lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="n"&gt;shared_counter&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;mutex&lt;/span&gt; &lt;span class="n"&gt;key&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="kt"&gt;void&lt;/span&gt; &lt;span class="nf"&gt;increment_counter&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="n"&gt;i&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt; &lt;span class="n"&gt;i&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&lt;/span&gt; &lt;span class="mi"&gt;100000&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt; &lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="o"&gt;++&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="n"&gt;key&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;lock&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;     &lt;span class="c1"&gt;// lock critical region&lt;/span&gt;
        &lt;span class="n"&gt;shared_counter&lt;/span&gt;&lt;span class="o"&gt;++&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
        &lt;span class="n"&gt;key&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;unlock&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;   &lt;span class="c1"&gt;// unlock critical region&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="nf"&gt;main&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="kr"&gt;thread&lt;/span&gt; &lt;span class="n"&gt;my_worker1&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;increment_counter&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
    &lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="kr"&gt;thread&lt;/span&gt; &lt;span class="n"&gt;my_worker2&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;increment_counter&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;

    &lt;span class="n"&gt;my_worker1&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;join&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;
    &lt;span class="n"&gt;my_worker2&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;join&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;

    &lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;cout&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&amp;lt;&lt;/span&gt; &lt;span class="s"&gt;"Final counter value: "&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&amp;lt;&lt;/span&gt; &lt;span class="n"&gt;shared_counter&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&amp;lt;&lt;/span&gt; &lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;endl&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;&lt;em&gt;&lt;code&gt;Explanation:&lt;/code&gt;&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;As you can see, we have created a &lt;code&gt;std::mutex&lt;/code&gt; object called &lt;code&gt;Key&lt;/code&gt;. By using the &lt;code&gt;lock()&lt;/code&gt; and &lt;code&gt;unlock()&lt;/code&gt; member functions of the &lt;code&gt;std::mutex&lt;/code&gt; class, a thread (given that it reaches the mutex first) will be able to lock and unlock the &lt;code&gt;shared_counter&lt;/code&gt; variable.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fois556jecqdkeg8ry9a3.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fois556jecqdkeg8ry9a3.gif" alt="Mutex Visualization GIF"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;While the critical region is locked, other threads outside will be blocked until the critical region gets unlocked. Thereby the data race between these two threads will be avoided.&lt;/p&gt;

&lt;p&gt;Blocking a thread in some cases may not be an optimal approach. To overcome that we can also use &lt;code&gt;std::mutex::try_lock()&lt;/code&gt; rather than &lt;code&gt;std::mutex::lock()&lt;/code&gt;.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight cpp"&gt;&lt;code&gt;

&lt;span class="kt"&gt;void&lt;/span&gt; &lt;span class="nf"&gt;increment_counter&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="n"&gt;i&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt; &lt;span class="n"&gt;i&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&lt;/span&gt; &lt;span class="mi"&gt;100000&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt; &lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="o"&gt;++&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="k"&gt;if&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;key&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;try_lock&lt;/span&gt;&lt;span class="p"&gt;())&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="c1"&gt;// try to lock critical region&lt;/span&gt;
            &lt;span class="n"&gt;shared_counter&lt;/span&gt;&lt;span class="o"&gt;++&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
            &lt;span class="n"&gt;key&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;unlock&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;   &lt;span class="c1"&gt;// unlock critical region&lt;/span&gt;
        &lt;span class="p"&gt;}&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;What this would do is instead of putting the thread in a block queue, it returns the boolean value &lt;code&gt;false&lt;/code&gt;, allowing the thread to try again later.&lt;/p&gt;

&lt;p&gt;Here, goes the visualization of what may happen if we introduce &lt;code&gt;try_lock()&lt;/code&gt; in our code.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fek9x0mkvpjuyj94x2k50.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fek9x0mkvpjuyj94x2k50.gif" alt="try_lock() visualization GIF"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;“With greater flexibility comes greater responsibility.”&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Although, &lt;code&gt;try_lock()&lt;/code&gt; is solving a key issue here but it may introduce unexpected code behaviours. Also if not implemented properly it may lead to a &lt;strong&gt;livelock&lt;/strong&gt; situation where two or more threads are constantly trying and failing to acquire the lock leading to wasted CPU cycles.&lt;/p&gt;

&lt;p&gt;That's why the C++ &lt;code&gt;std::thread&lt;/code&gt; library provides a special kind of mutex class called &lt;code&gt;std::timed_mutex&lt;/code&gt; which comes with the &lt;code&gt;std::timed_mutex::try_lock_for()&lt;/code&gt; and &lt;code&gt;std::timed_mutex::try_lock_until()&lt;/code&gt; member functions.&lt;/p&gt;

&lt;h2&gt;
  
  
  Deadlock and Livelock:
&lt;/h2&gt;

&lt;p&gt;A &lt;strong&gt;deadlock&lt;/strong&gt; situation occurs when two or more blocked threads are waiting for each other to release a resource such as a mutex, which never gets released, resulting in the threads stopping their execution and waiting for an indefinite amount of time.&lt;/p&gt;

&lt;p&gt;As bad as it sounds, deadlocks can easily hang our applications for an indefinite amount of time unless some external intervention occurs.&lt;/p&gt;

&lt;p&gt;Let's try to recreate a deadlock situation,&lt;/p&gt;

&lt;p&gt;&lt;em&gt;&lt;code&gt;Code Example:&lt;/code&gt;&lt;/em&gt;&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight cpp"&gt;&lt;code&gt;

&lt;span class="cp"&gt;#include&lt;/span&gt; &lt;span class="cpf"&gt;&amp;lt;iostream&amp;gt;&lt;/span&gt;&lt;span class="cp"&gt;
#include&lt;/span&gt; &lt;span class="cpf"&gt;&amp;lt;thread&amp;gt;&lt;/span&gt;&lt;span class="cp"&gt;
#include&lt;/span&gt; &lt;span class="cpf"&gt;&amp;lt;mutex&amp;gt;&lt;/span&gt;&lt;span class="cp"&gt;
#include&lt;/span&gt; &lt;span class="cpf"&gt;&amp;lt;vector&amp;gt;&lt;/span&gt;&lt;span class="cp"&gt;
&lt;/span&gt;
&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;mutex&lt;/span&gt; &lt;span class="n"&gt;cout_key&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="kt"&gt;void&lt;/span&gt; &lt;span class="nf"&gt;my_work&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="n"&gt;cout_key&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;lock&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;
    &lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;cout&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&amp;lt;&lt;/span&gt; &lt;span class="s"&gt;"Thread"&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&amp;lt;&lt;/span&gt; &lt;span class="sc"&gt;'['&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&amp;lt;&lt;/span&gt; &lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;this_thread&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;get_id&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&amp;lt;&lt;/span&gt; &lt;span class="sc"&gt;']'&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&amp;lt;&lt;/span&gt; &lt;span class="s"&gt;" acquired the lock"&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&amp;lt;&lt;/span&gt; &lt;span class="sc"&gt;'\n'&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="c1"&gt;//cout_key.unlock();&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="nf"&gt;main&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;vector&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="kr"&gt;thread&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;my_threads&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="k"&gt;for&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt; &lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt; &lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="o"&gt;++&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="n"&gt;my_threads&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;emplace_back&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;my_work&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;
    &lt;span class="k"&gt;for&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="k"&gt;auto&lt;/span&gt;&lt;span class="o"&gt;&amp;amp;&lt;/span&gt; &lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="o"&gt;:&lt;/span&gt; &lt;span class="n"&gt;my_threads&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;join&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;One of the simplest kinds of deadlock can occur when a lock is acquired by a thread but never released.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fhn97omuqw3x0e6vrbgf6.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fhn97omuqw3x0e6vrbgf6.gif" alt="Deadlock Visualization GIF"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;In this example, the thread that locks the mutex first will print the output without releasing the lock, causing the other thread to be blocked upon attempting to acquire the lock and unable to proceed further.&lt;/p&gt;

&lt;p&gt;A &lt;strong&gt;livelock&lt;/strong&gt; situation, on the other hand, is similar to the deadlock situation but in this case, instead of the threads getting blocked, they constantly run on an active checking loop consuming CPU resources without making any real progress.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;&lt;code&gt;Code Example:&lt;/code&gt;&lt;/em&gt;&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight cpp"&gt;&lt;code&gt;

&lt;span class="cp"&gt;#include&lt;/span&gt; &lt;span class="cpf"&gt;&amp;lt;iostream&amp;gt;&lt;/span&gt;&lt;span class="cp"&gt;
#include&lt;/span&gt; &lt;span class="cpf"&gt;&amp;lt;thread&amp;gt;&lt;/span&gt;&lt;span class="cp"&gt;
#include&lt;/span&gt; &lt;span class="cpf"&gt;&amp;lt;mutex&amp;gt;&lt;/span&gt;&lt;span class="cp"&gt;
#include&lt;/span&gt; &lt;span class="cpf"&gt;&amp;lt;vector&amp;gt;&lt;/span&gt;&lt;span class="cp"&gt;
&lt;/span&gt;
&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;mutex&lt;/span&gt; &lt;span class="n"&gt;cout_key&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="kt"&gt;void&lt;/span&gt; &lt;span class="nf"&gt;my_work&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="k"&gt;while&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nb"&gt;true&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="k"&gt;if&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;cout_key&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;try_lock&lt;/span&gt;&lt;span class="p"&gt;())&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
            &lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;cout&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&amp;lt;&lt;/span&gt; &lt;span class="s"&gt;"Thread"&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&amp;lt;&lt;/span&gt; &lt;span class="sc"&gt;'['&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&amp;lt;&lt;/span&gt; &lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;this_thread&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;get_id&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&amp;lt;&lt;/span&gt; &lt;span class="sc"&gt;']'&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&amp;lt;&lt;/span&gt; &lt;span class="s"&gt;" acquired the lock&lt;/span&gt;&lt;span class="se"&gt;\n&lt;/span&gt;&lt;span class="s"&gt;"&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
            &lt;span class="c1"&gt;//cout_key.unlock();&lt;/span&gt;
            &lt;span class="k"&gt;return&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
        &lt;span class="p"&gt;}&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="nf"&gt;main&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;vector&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="kr"&gt;thread&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;my_threads&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="k"&gt;for&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt; &lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt; &lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="o"&gt;++&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="n"&gt;my_threads&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;emplace_back&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;my_work&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;
    &lt;span class="k"&gt;for&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="k"&gt;auto&lt;/span&gt;&lt;span class="o"&gt;&amp;amp;&lt;/span&gt; &lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="o"&gt;:&lt;/span&gt; &lt;span class="n"&gt;my_threads&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;join&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fk40pnvk03i2m5gqg0i3m.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fk40pnvk03i2m5gqg0i3m.gif" alt="Livelock Visualization GIF"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Similar to the previous scenario, the thread that acquires the &lt;code&gt;cout_key&lt;/code&gt; mutex first will print the output without releasing it. As a result, the second thread will attempt to acquire the mutex and enter an infinite loop.&lt;/p&gt;

&lt;p&gt;Whether it is a deadlock or a livelock, it is indeed one of the worst problems to face while developing any multithreaded applications. &lt;/p&gt;

&lt;p&gt;To avoid situations like this, we can follow some guidelines, such as keeping the critical section short, following a specific order of mutexes, and putting a time bound on the waiting part. &lt;/p&gt;

&lt;p&gt;We can also use some of the C++ features while working with locks, such as using RAII (i.e. scoped bound resource management) like &lt;code&gt;std::lock_guard&lt;/code&gt;, or using &lt;code&gt;std::scoped_lock&lt;/code&gt; to acquire more than one lock.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;"Prevention is better than a cure"&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;In conclusion, threads can be a bit of a hassle to debug, and that's why it is important to follow the best practices from the very beginning so that at the end it doesn't become unmanageable and time-consuming to identify and fix bugs.&lt;/p&gt;

</description>
      <category>programming</category>
      <category>tutorial</category>
      <category>cpp</category>
      <category>performance</category>
    </item>
    <item>
      <title>Multithreading | How to Create and Manage Threads in C++</title>
      <dc:creator>Shreyos Ghosh</dc:creator>
      <pubDate>Wed, 23 Nov 2022 16:03:27 +0000</pubDate>
      <link>https://dev.to/shreyosghosh/working-with-threads-in-c-part-1-5el3</link>
      <guid>https://dev.to/shreyosghosh/working-with-threads-in-c-part-1-5el3</guid>
      <description>&lt;p&gt;In any language, threads can be a very useful tool to do a certain task more efficiently by allowing the program to do multiple operations (e.g. input, processing, storage and output) at the same time. Threads can be utilized to allocate and execute different parts of a program without interrupting the main program.&lt;/p&gt;

&lt;p&gt;Here, I will briefly talk about concurrency and parallelism as well as how you can implement multithreading in your C++ program.&lt;/p&gt;

&lt;h1&gt;
  
  
  What's a Thread?
&lt;/h1&gt;

&lt;p&gt;A thread is a sequence of instructions that run in parallel to other threads within a process.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;em&gt;A process is a program which is under execution i.e. when a program is loaded into the memory then it becomes a process.&lt;/em&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Now, that we know about threads, let's see the differences between concurrency and parallelism&lt;/p&gt;

&lt;h2&gt;
  
  
  Concurrency vs. Parallelism
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Concurrency&lt;/strong&gt; is closely related to multithreading, where more than one or many threads are handled at a period of time by switching the control from one thread to another back and forth. It may seem like all the threads are being executed at the same time. As this whole process is very quick but in reality, only one thread can be handled at a time. In concurrency, multiple threads can communicate with each other.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Parallelism&lt;/strong&gt; is achieved when multiple threads are handled parallel to each other in hardware resources (multi-core, multi-chip or many cores).&lt;/p&gt;

&lt;p&gt;Let's explain these two terms with a real-life example. Suppose there is one ticket counter managing two queues. Where only one person is getting a ticket at a time but that person can be from any queue. Here, if one queue is getting served then the other queue has to wait for it's turn and vice versa. This is an example of concurrency.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fdb9h07vkevi2mfvd8v0z.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fdb9h07vkevi2mfvd8v0z.png" alt="Diagram of Concurrency"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Now, if we increase the number of counters and make it two, then each queue gets it's own ticket counter and they can be managed in a parallel manner.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F424y8u3yh5xkebnen7a7.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F424y8u3yh5xkebnen7a7.png" alt="Diagram of Parallelism"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Here, as we can see each counter can only handle one customer or queue at a time. Similarly, consider these queues as a thread and counters as a core of a CPU with each core having the ability to handle only one thread at once, that's what we call a single-threaded core.&lt;/p&gt;

&lt;p&gt;Now if you have two threads to run in a single-threaded core, then you need to run them in a concurrent manner(i.e. having two queues with only one counter).&lt;/p&gt;

&lt;p&gt;But when you have more than one single-threaded core then you have the ability to run those two threads parallelly(i.e. having two queues with two counters/one counter each).&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;em&gt;Concurrency --&amp;gt; Illusion&lt;/em&gt;&lt;br&gt;
&lt;em&gt;Parallelism --&amp;gt; True Concurrency&lt;/em&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Nowadays, we can actually run two threads in one core at once (you can visualize them as a bigger core which is logically divided into two sub-core/smaller-core) which is also termed as &lt;strong&gt;hyperthreading&lt;/strong&gt;.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;em&gt;For those who have confusion with the term "thread" being used by those CPU manufacturing companies vs. in software. What these companies mean by saying their CPU has "X" amount of threads, is actually how many threads that the CPU can run parallelly. But this doesn't mean that your CPU is limited to run only "X" amount of threads. Obviously, your CPU can run thousands of threads concurrently, but in that case, some threads will have to share hardware resources.&lt;/em&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h1&gt;
  
  
  Managing Threads:
&lt;/h1&gt;

&lt;p&gt;Up to this point, we've gained a little bit of understanding about multithreading. So let's have a look at how we can launch/create multiple threads in our C++ code.&lt;/p&gt;

&lt;h2&gt;
  
  
  Create a Thread:
&lt;/h2&gt;

&lt;p&gt;There are three possible ways that we can create a thread. Which are,&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Using Function Pointer&lt;/strong&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Using Function Object&lt;/strong&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Using Lambda Expression&lt;/strong&gt;&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Note: To work with threads, we will have to use the &lt;code&gt;C++&lt;/code&gt; standard library header &lt;code&gt;&amp;lt;thread&amp;gt;&lt;/code&gt;. Every C++ program has at least one thread on which &lt;code&gt;main()&lt;/code&gt; is called at program startup, it is called a &lt;strong&gt;main thread&lt;/strong&gt;.&lt;/p&gt;

&lt;h3&gt;
  
  
  Using Function Pointer:
&lt;/h3&gt;

&lt;p&gt;Here, we will pass a &lt;strong&gt;function pointer&lt;/strong&gt; as a task for the &lt;strong&gt;thread object&lt;/strong&gt; of &lt;code&gt;std::thread&lt;/code&gt; &lt;strong&gt;class&lt;/strong&gt;.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

1. void my_task(parameters);  //callable function
2. std::thread my_worker(my_task, arguments);  //construction of
   //thread object specifying the task.


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;&lt;em&gt;&lt;code&gt;Code Example:&lt;/code&gt;&lt;/em&gt;&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight cpp"&gt;&lt;code&gt;

&lt;span class="cp"&gt;#include&lt;/span&gt; &lt;span class="cpf"&gt;&amp;lt;iostream&amp;gt;&lt;/span&gt;&lt;span class="cp"&gt;
#include&lt;/span&gt; &lt;span class="cpf"&gt;&amp;lt;thread&amp;gt;&lt;/span&gt;&lt;span class="cp"&gt;
&lt;/span&gt;
&lt;span class="kt"&gt;void&lt;/span&gt; &lt;span class="nf"&gt;my_task&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;string&lt;/span&gt; &lt;span class="n"&gt;name&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;cout&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&amp;lt;&lt;/span&gt; &lt;span class="s"&gt;"Hello world of "&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&amp;lt;&lt;/span&gt; &lt;span class="n"&gt;name&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&amp;lt;&lt;/span&gt; &lt;span class="s"&gt;"&lt;/span&gt;&lt;span class="se"&gt;\n&lt;/span&gt;&lt;span class="s"&gt;"&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="nf"&gt;main&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="kr"&gt;thread&lt;/span&gt; &lt;span class="n"&gt;my_worker&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;my_task&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s"&gt;"thread!"&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
    &lt;span class="n"&gt;my_worker&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;join&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;&lt;em&gt;&lt;code&gt;Explanation:&lt;/code&gt;&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;As I said, we are passing a function pointer &lt;code&gt;my_task&lt;/code&gt; as a task to the thread object &lt;code&gt;my_worker&lt;/code&gt; and as soon as the construction of the thread object is done, the thread starts the execution of the said task.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;em&gt;In total there are two threads present in the above program, one is the &lt;strong&gt;main thread&lt;/strong&gt; and another one is the &lt;strong&gt;worker thread&lt;/strong&gt;.&lt;/em&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Notice, that here I've used thread join method &lt;code&gt;join()&lt;/code&gt;, which we'll talk about later.&lt;/p&gt;

&lt;h3&gt;
  
  
  Using Function Object:
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Function object&lt;/strong&gt; which is also called as a &lt;strong&gt;functor&lt;/strong&gt;, can be used to pass a callable &lt;strong&gt;object&lt;/strong&gt;/&lt;strong&gt;instance&lt;/strong&gt; of a class as a task to the thread object by overloading the function call operator &lt;code&gt;()&lt;/code&gt; using operator function.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;em&gt;&lt;strong&gt;object&lt;/strong&gt; + &lt;strong&gt;()&lt;/strong&gt; = &lt;strong&gt;functor&lt;/strong&gt;/&lt;strong&gt;function object&lt;/strong&gt;&lt;/em&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

1. class my_functor {  //function object class
   public:
       void operator()(parameters) {  //operator function 
           //task list                //overloading () operator
       }
   };
2. my_functor Functor;  //declaration of object
3. std::thread my_worker(Functor, arguments);  //construction
   //of thread object using functor


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;&lt;em&gt;&lt;code&gt;Code Example:&lt;/code&gt;&lt;/em&gt;&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight cpp"&gt;&lt;code&gt;

&lt;span class="cp"&gt;#include&lt;/span&gt; &lt;span class="cpf"&gt;&amp;lt;iostream&amp;gt;&lt;/span&gt;&lt;span class="cp"&gt;
#include&lt;/span&gt; &lt;span class="cpf"&gt;&amp;lt;thread&amp;gt;&lt;/span&gt;&lt;span class="cp"&gt;
&lt;/span&gt;
&lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;my_functor&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="nl"&gt;public:&lt;/span&gt;
    &lt;span class="c1"&gt;//operator overloading&lt;/span&gt;
    &lt;span class="kt"&gt;void&lt;/span&gt; &lt;span class="k"&gt;operator&lt;/span&gt;&lt;span class="p"&gt;()(&lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;string&lt;/span&gt; &lt;span class="n"&gt;name&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;cout&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&amp;lt;&lt;/span&gt; &lt;span class="s"&gt;"Hello it's me, "&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&amp;lt;&lt;/span&gt; &lt;span class="n"&gt;name&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;};&lt;/span&gt;
&lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="nf"&gt;main&lt;/span&gt;&lt;span class="p"&gt;(){&lt;/span&gt;
    &lt;span class="n"&gt;my_functor&lt;/span&gt; &lt;span class="n"&gt;Functor&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="kr"&gt;thread&lt;/span&gt; &lt;span class="n"&gt;my_worker&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;Functor&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s"&gt;"Functor!"&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
    &lt;span class="n"&gt;my_worker&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;join&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;&lt;em&gt;&lt;code&gt;Explanation:&lt;/code&gt;&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Here, we are passing a function object &lt;code&gt;Functor()&lt;/code&gt; which belongs to the function object class &lt;code&gt;my_functor&lt;/code&gt; as a task to the thread object &lt;code&gt;my_worker&lt;/code&gt;, by overloading the function call operator/parenthesis operator &lt;code&gt;()&lt;/code&gt;.&lt;/p&gt;

&lt;h3&gt;
  
  
  Using Lambda Expression:
&lt;/h3&gt;

&lt;p&gt;A &lt;strong&gt;lambda Expression&lt;/strong&gt;, which consists of a nameless function, can be passed as a task (i.e. a callable type) to the &lt;strong&gt;thread object&lt;/strong&gt;.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

1. auto my_lambda_exp = [capture clause](parameters) {
         //task list                    //lambda expression
   };
2. std::thread my_worker (my_lambda_exp, arguments);
   //construction of thread object using lambda expression


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;&lt;em&gt;&lt;code&gt;Code Example:&lt;/code&gt;&lt;/em&gt;&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight cpp"&gt;&lt;code&gt;

&lt;span class="cp"&gt;#include&lt;/span&gt; &lt;span class="cpf"&gt;&amp;lt;iostream&amp;gt;&lt;/span&gt;&lt;span class="cp"&gt;
#include&lt;/span&gt; &lt;span class="cpf"&gt;&amp;lt;thread&amp;gt;&lt;/span&gt;&lt;span class="cp"&gt;
&lt;/span&gt;
&lt;span class="k"&gt;auto&lt;/span&gt; &lt;span class="n"&gt;my_lambda_exp&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;[](&lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;string&lt;/span&gt; &lt;span class="n"&gt;name&lt;/span&gt;&lt;span class="p"&gt;){&lt;/span&gt;
    &lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;cout&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&amp;lt;&lt;/span&gt; &lt;span class="s"&gt;"Hello "&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&amp;lt;&lt;/span&gt; &lt;span class="n"&gt;name&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="p"&gt;};&lt;/span&gt;

&lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="nf"&gt;main&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="kr"&gt;thread&lt;/span&gt; &lt;span class="n"&gt;my_worker&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;my_lambda_exp&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s"&gt;"World!"&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
    &lt;span class="n"&gt;my_worker&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;join&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;&lt;em&gt;&lt;code&gt;Explanation:&lt;/code&gt;&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Here, we are using a variable &lt;code&gt;my_lambda_exp&lt;/code&gt; and passing it as a callable type for the thread object &lt;code&gt;my_worker&lt;/code&gt; .&lt;br&gt;
The lambda expression,&lt;br&gt;
&lt;code&gt;[](std::string name){std::cout &amp;lt;&amp;lt; "Hello " &amp;lt;&amp;lt; name;}&lt;/code&gt;&lt;br&gt;
which is assigned to the variable &lt;code&gt;my_lambda_exp&lt;/code&gt;, can also be used as a task for the thread object.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;&lt;code&gt;Code Snippet:&lt;/code&gt;&lt;/em&gt;&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight cpp"&gt;&lt;code&gt;

&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="kr"&gt;thread&lt;/span&gt; &lt;span class="nf"&gt;my_worker&lt;/span&gt; &lt;span class="p"&gt;([](&lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;string&lt;/span&gt; &lt;span class="n"&gt;name&lt;/span&gt;&lt;span class="p"&gt;){&lt;/span&gt;
    &lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;cout&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&amp;lt;&lt;/span&gt; &lt;span class="s"&gt;"Hello "&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&amp;lt;&lt;/span&gt; &lt;span class="n"&gt;name&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="p"&gt;},&lt;/span&gt; &lt;span class="s"&gt;"World!"&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;For this case, you don't need to assign the lambda expression to a variable. You can put it directly and it will be treated as a callable type. Both of the given examples will work the same.&lt;/p&gt;

&lt;p&gt;Now, it's time to talk about that &lt;code&gt;join()&lt;/code&gt; method that we previously used.&lt;/p&gt;

&lt;h2&gt;
  
  
  Join and Detach a Thread:
&lt;/h2&gt;

&lt;p&gt;When you launch a thread object, as said the thread will start the process of execution. At this point, you have the main thread and a worker thread running.&lt;/p&gt;

&lt;p&gt;Now, you have two options either you can use &lt;code&gt;join()&lt;/code&gt; i.e. pause the main thread and wait for the worker thread to complete the task and then continue the main thread execution or you can use &lt;code&gt;detach()&lt;/code&gt; and continue the main thread execution and forget about the worker thread.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;em&gt;It is mandatory to either join or detach a thread before the main program execution is completed or it will be considered as an error and the&lt;/em&gt; &lt;code&gt;std::terminate&lt;/code&gt; &lt;em&gt;will be called by the thread destructor&lt;/em&gt; &lt;code&gt;std::thread::~thread&lt;/code&gt; &lt;em&gt;for garbage collection.&lt;/em&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h3&gt;
  
  
  Joining a thread:
&lt;/h3&gt;

&lt;p&gt;Let me give you a code example, &lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

1. void my_work(parameters);  //callable function
2. std::thread my_worker(my_work, arguments);  //construction of
   //thread object passing the task
3. my_worker.join();  //joining the worker thread


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;&lt;em&gt;&lt;code&gt;Code Example:&lt;/code&gt;&lt;/em&gt;&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight cpp"&gt;&lt;code&gt;

&lt;span class="cp"&gt;#include&lt;/span&gt; &lt;span class="cpf"&gt;&amp;lt;iostream&amp;gt;&lt;/span&gt;&lt;span class="cp"&gt;
#include&lt;/span&gt; &lt;span class="cpf"&gt;&amp;lt;thread&amp;gt;&lt;/span&gt;&lt;span class="cp"&gt;
&lt;/span&gt;
&lt;span class="kt"&gt;void&lt;/span&gt; &lt;span class="nf"&gt;my_work&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="n"&gt;count&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="k"&gt;while&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;count&lt;/span&gt;&lt;span class="o"&gt;++&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&lt;/span&gt; &lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;){&lt;/span&gt;
        &lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;cout&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&amp;lt;&lt;/span&gt; &lt;span class="s"&gt;"Worker thread is working..."&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&amp;lt;&lt;/span&gt; &lt;span class="s"&gt;"&lt;/span&gt;&lt;span class="se"&gt;\n&lt;/span&gt;&lt;span class="s"&gt;"&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;
    &lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;cout&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&amp;lt;&lt;/span&gt; &lt;span class="s"&gt;"The task is completed!"&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&amp;lt;&lt;/span&gt; &lt;span class="s"&gt;"&lt;/span&gt;&lt;span class="se"&gt;\n&lt;/span&gt;&lt;span class="s"&gt;"&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="nf"&gt;main&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;cout&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&amp;lt;&lt;/span&gt; &lt;span class="s"&gt;"This is main thread!"&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&amp;lt;&lt;/span&gt; &lt;span class="s"&gt;"&lt;/span&gt;&lt;span class="se"&gt;\n&lt;/span&gt;&lt;span class="s"&gt;"&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="kr"&gt;thread&lt;/span&gt; &lt;span class="n"&gt;my_worker&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;my_work&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
    &lt;span class="n"&gt;my_worker&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;join&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;
    &lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;cout&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&amp;lt;&lt;/span&gt; &lt;span class="s"&gt;"Main thread execution completed!"&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&amp;lt;&lt;/span&gt; &lt;span class="s"&gt;"&lt;/span&gt;&lt;span class="se"&gt;\n&lt;/span&gt;&lt;span class="s"&gt;"&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;&lt;em&gt;&lt;code&gt;Code Output:&lt;/code&gt;&lt;/em&gt;&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

 This is main thread!
 Worker thread is working...
 Worker thread is working...
 The task is completed!
 Main thread execution completed!


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;&lt;em&gt;&lt;code&gt;Explanation:&lt;/code&gt;&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Felpfal4kd34oeltzvx65.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Felpfal4kd34oeltzvx65.png" alt="Thread Joining"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;In the above program, after passing the function pointer &lt;code&gt;my_work&lt;/code&gt; to the thread object &lt;code&gt;my_worker&lt;/code&gt;, we've called the &lt;code&gt;join()&lt;/code&gt; method and because of this, the main thread execution will be paused until the given task for the worker thread is done.&lt;/p&gt;

&lt;p&gt;Before talking about the detach method, let's understand&lt;/p&gt;

&lt;h3&gt;
  
  
  What is &lt;code&gt;joinable()&lt;/code&gt;?
&lt;/h3&gt;

&lt;p&gt;&lt;code&gt;std::thread::&lt;/code&gt;joinable is a method used to check if a thread has been joined/detached or not.&lt;/p&gt;

&lt;p&gt;By default, every constructed thread object is joinable, Which means &lt;code&gt;joinable() == true&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;If not changed as usual this will trigger an error and the destructor &lt;code&gt;std::thread::~thread&lt;/code&gt; will terminate the program by the end of the main program execution. Once a thread object is joined/detached &lt;code&gt;joinable() == false&lt;/code&gt;. &lt;/p&gt;

&lt;h3&gt;
  
  
  Detaching a thread:
&lt;/h3&gt;

&lt;p&gt;Let's say you're in such a scenario, where you don't want to pause the execution of the main program or the task for the worker thread is going to take a lot of time that you can't afford to wait on. That's when you can use &lt;code&gt;detach()&lt;/code&gt; to run your thread in the background.&lt;/p&gt;

&lt;p&gt;By using detach method we can execute the main thread and the worker thread (i.e. the caller thread and the called thread) independently from each other. And as soon as either one's execution ends, the thread destructor &lt;code&gt;std::thread::~thread&lt;/code&gt; will be called and the resources will be released.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

1. void my_work(parameters);  //callable function
2. std::thread my_worker(my_work, arguments);  //construction of
   //thread object passing the task
3. my_worker.detach();  //detaching the worker thread


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;&lt;em&gt;&lt;code&gt;Code Example:&lt;/code&gt;&lt;/em&gt;&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight cpp"&gt;&lt;code&gt;

&lt;span class="cp"&gt;#include&lt;/span&gt; &lt;span class="cpf"&gt;&amp;lt;iostream&amp;gt;&lt;/span&gt;&lt;span class="cp"&gt;
#include&lt;/span&gt; &lt;span class="cpf"&gt;&amp;lt;chrono&amp;gt;&lt;/span&gt;&lt;span class="cp"&gt;
#include&lt;/span&gt; &lt;span class="cpf"&gt;&amp;lt;thread&amp;gt;&lt;/span&gt;&lt;span class="cp"&gt;
&lt;/span&gt;&lt;span class="k"&gt;using&lt;/span&gt; &lt;span class="k"&gt;namespace&lt;/span&gt; &lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;this_thread&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="k"&gt;using&lt;/span&gt; &lt;span class="k"&gt;namespace&lt;/span&gt; &lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;chrono&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="kt"&gt;void&lt;/span&gt; &lt;span class="nf"&gt;my_work&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="n"&gt;count&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="k"&gt;while&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;count&lt;/span&gt;&lt;span class="o"&gt;++&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&lt;/span&gt; &lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;){&lt;/span&gt;
        &lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;cout&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&amp;lt;&lt;/span&gt; &lt;span class="s"&gt;"Worker thread is working..."&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&amp;lt;&lt;/span&gt; &lt;span class="s"&gt;"&lt;/span&gt;&lt;span class="se"&gt;\n&lt;/span&gt;&lt;span class="s"&gt;"&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;
    &lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;cout&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&amp;lt;&lt;/span&gt; &lt;span class="s"&gt;"The task is completed!"&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&amp;lt;&lt;/span&gt; &lt;span class="s"&gt;"&lt;/span&gt;&lt;span class="se"&gt;\n&lt;/span&gt;&lt;span class="s"&gt;"&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="nf"&gt;main&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;cout&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&amp;lt;&lt;/span&gt; &lt;span class="s"&gt;"This is main thread!"&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&amp;lt;&lt;/span&gt; &lt;span class="s"&gt;"&lt;/span&gt;&lt;span class="se"&gt;\n&lt;/span&gt;&lt;span class="s"&gt;"&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="kr"&gt;thread&lt;/span&gt; &lt;span class="n"&gt;my_worker&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;my_work&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
    &lt;span class="n"&gt;my_worker&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;detach&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;
    &lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;cout&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&amp;lt;&lt;/span&gt; &lt;span class="s"&gt;"Main thread execution completed!"&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&amp;lt;&lt;/span&gt; &lt;span class="s"&gt;"&lt;/span&gt;&lt;span class="se"&gt;\n&lt;/span&gt;&lt;span class="s"&gt;"&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="c1"&gt;//sleep_until(system_clock::now() + seconds(2));&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;&lt;em&gt;&lt;code&gt;Code Output:&lt;/code&gt;&lt;/em&gt;&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

This is main thread!
Main thread execution completed!


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;&lt;em&gt;&lt;code&gt;Explanation:&lt;/code&gt;&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fnw1e42tzds71xoo3c5ta.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fnw1e42tzds71xoo3c5ta.png" alt="Thread Detaching"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;If you run the given example code, you'll probably get an output like that.&lt;/p&gt;

&lt;p&gt;So, let's talk about why this is happening...&lt;/p&gt;

&lt;p&gt;I previously said that as soon as the construction of the thread object(of the worker thread) is done, the thread(worker thread) starts the execution of the said task.&lt;/p&gt;

&lt;p&gt;Now there is a little more to be told! Let me explain...&lt;/p&gt;

&lt;p&gt;When we construct a thread object and pass a callable type to it, first the OS collects the request and only then it initiates the execution. As it sounds this whole operation is not instantaneous.&lt;/p&gt;

&lt;p&gt;Now when you're using the detach method, that means the underlying thread will be detached from the thread object and main thread won't be paused rather it'll continue to run until the flow of the program reaches the end. Which is much quicker in this case. That's why we are not getting the desired output from the worker thread.&lt;/p&gt;

&lt;p&gt;But if you &lt;strong&gt;undo the commented line&lt;/strong&gt; in the above code, which will let the worker thread to complete it's task by putting the main program into sleep for 2 seconds, then you'll get this output&lt;/p&gt;

&lt;p&gt;&lt;em&gt;&lt;code&gt;Code Output:&lt;/code&gt;&lt;/em&gt;&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

This is main thread!
Main thread execution completed!
Worker thread is working...
Worker thread is working...
The task is completed!


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;blockquote&gt;
&lt;p&gt;Funfact: Threads might not be as evil as you thought!&lt;/p&gt;
&lt;/blockquote&gt;

</description>
      <category>programming</category>
      <category>tutorial</category>
      <category>cpp</category>
      <category>performance</category>
    </item>
  </channel>
</rss>
