<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Harish Kant Soni on Medium]]></title>
        <description><![CDATA[Stories by Harish Kant Soni on Medium]]></description>
        <link>https://medium.com/@hksoni?source=rss-9be79c07dba------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*bt38bcaMg_kIvOCr</url>
            <title>Stories by Harish Kant Soni on Medium</title>
            <link>https://medium.com/@hksoni?source=rss-9be79c07dba------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 12:08:01 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@hksoni/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Declaring a destructor turns a move into a copy]]></title>
            <link>https://hksoni.medium.com/declaring-a-destructor-turns-a-move-into-a-copy-3813200e574b?source=rss-9be79c07dba------2</link>
            <guid isPermaLink="false">https://medium.com/p/3813200e574b</guid>
            <category><![CDATA[cplusplus]]></category>
            <category><![CDATA[c-plus-plus-language]]></category>
            <dc:creator><![CDATA[Harish Kant Soni]]></dc:creator>
            <pubDate>Sat, 26 Sep 2026 06:42:54 GMT</pubDate>
            <atom:updated>2026-09-26T06:42:54.459Z</atom:updated>
            <content:encoded><![CDATA[<p>Below is a code snippet with two classes that do identical work, except one defines a destructor that does nothing and the other doesn’t. Just by defining that destructor, the move operation took 1,546,342 ns, whereas earlier it was taking 114 ns — about ≈ 13,000 times slower.</p><pre>#include &lt;iostream&gt;<br>#include &lt;vector&gt;<br>#include &lt;chrono&gt;<br>using namespace std;<br><br>struct SomeContainer{<br>    vector&lt;int&gt; v;<br>    SomeContainer(){<br>        for(int i=0;i&lt;1e6;i++){<br>            v.push_back(i*i);<br>        }<br>    }<br>};<br><br>struct SomeContainerWithMoveDisabled{<br>    vector&lt;int&gt; v;<br>    SomeContainerWithMoveDisabled(){<br>        for(int i=0;i&lt;1e6;i++){<br>            v.push_back(i*i);<br>        }<br>    }<br>    ~SomeContainerWithMoveDisabled() = default;<br>};<br><br>int main(){<br>    SomeContainer c;<br><br>    auto start = chrono::high_resolution_clock::now();<br>    SomeContainer c2(c);<br>    auto end = chrono::high_resolution_clock::now();<br>    <br>    auto duration = chrono::duration_cast&lt;chrono::nanoseconds&gt;(end - start);<br>    cout &lt;&lt; &quot;Time taken in copy: &quot; &lt;&lt; duration.count() &lt;&lt; &quot; nanoseconds&quot; &lt;&lt; endl;<br><br>    start = chrono::high_resolution_clock::now();<br>    SomeContainer c3(move(c));<br>    end = chrono::high_resolution_clock::now();<br><br>    auto durationNs = chrono::duration_cast&lt;chrono::nanoseconds&gt;(end - start);<br>    cout &lt;&lt; &quot;Time taken in move: &quot; &lt;&lt; durationNs.count() &lt;&lt; &quot; nanoseconds&quot; &lt;&lt; endl;<br><br>    SomeContainerWithMoveDisabled cmd;<br><br>    start = chrono::high_resolution_clock::now();<br>    SomeContainerWithMoveDisabled cmd2(cmd);<br>    end = chrono::high_resolution_clock::now();<br><br>    duration = chrono::duration_cast&lt;chrono::nanoseconds&gt;(end - start);<br>    cout &lt;&lt; &quot;Time taken in copy (move disabled): &quot; &lt;&lt; duration.count() &lt;&lt; &quot; nanoseconds&quot; &lt;&lt; endl;<br><br>    start = chrono::high_resolution_clock::now();<br>    SomeContainerWithMoveDisabled cmd3(move(cmd));<br>    end = chrono::high_resolution_clock::now();<br><br>    durationNs = chrono::duration_cast&lt;chrono::nanoseconds&gt;(end - start);<br>    cout &lt;&lt; &quot;Time taken in move (move disabled): &quot; &lt;&lt; durationNs.count() &lt;&lt; &quot; nanoseconds&quot; &lt;&lt; endl;<br><br>    return 0;<br>}<br><br></pre><pre>Time taken in copy: 1602006 nanoseconds<br>Time taken in move: 114 nanoseconds<br>Time taken in copy (move disabled): 1523249 nanoseconds<br>Time taken in move (move disabled): 1546342 nanoseconds</pre><p>Here’s the difference between them, in full:</p><pre>~SomeContainerWithMoveDisabled() = default;</pre><p>That’s it. One empty destructor. Here’s how it costs you a millisecond and a half.</p><h3>You get five functions for free</h3><p>Declare nothing, and the compiler writes five functions for you: a destructor, a copy constructor, copy assignment, a move constructor, and move assignment.</p><p>SomeContainer does exactly that, which is why moving it is nearly free. A vector&lt;int&gt; moves by handing over its content.</p><h3>Then you write a destructor</h3><p>Now the compiler changes its mind about you. Its logic goes: you wrote a destructor, so you must be cleaning something up. Heap memory, a file handle, something like that. And anything owning raw memory needs real copy and move logic, not the naive member-by-member kind that leaves two objects pointing at the same buffer.</p><p>So it stops guessing, and refuses to write your move operations.</p><blockquote>Notice what it never checked: whether the destructor actually does anything. Mine is = default. It&#39;s empty. Doesn&#39;t matter. You declared it, and that&#39;s enough.</blockquote><h3>But copy sticks around</h3><p>For backward compatibly reasons compiler still generates copy ctor but not move ctor.</p><blockquote>// you get this auto generated<br>SomeContainerWithMoveDisabled(const SomeContainerWithMoveDisabled&amp;);</blockquote><blockquote>// you don’t this<br>S̶o̶m̶e̶C̶o̶n̶t̶a̶i̶n̶e̶r̶W̶i̶t̶h̶M̶o̶v̶e̶D̶i̶s̶a̶b̶l̶e̶d̶(̶S̶o̶m̶e̶C̶o̶n̶t̶a̶i̶n̶e̶r̶W̶i̶t̶h̶M̶o̶v̶e̶D̶i̶s̶a̶b̶l̶e̶d̶&amp;̶&amp;̶)̶;̶</blockquote><p>The move constructor isn’t deleted. It just isn’t there.</p><p>If it were deleted, your move() call would still pick it, fail, and hand you a compiler error.</p><p>Instead there’s nothing to pick but the copy constructor. And std::move doesn&#39;t move anything, remember. It only casts its argument to an rvalue. Which binds to a const&amp; parameter without complaint.</p><p>In other words, SomeContainerWithMoveDisabled cmd3(move(cmd)); triggers call to SomeContainerWithMoveDisabled(const SomeContainerWithMoveDisabled&amp;); which is compiler generated copy ctor. This happes because</p><pre>SomeContainerWithMoveDisabled cmd3(move(cmd));<br><br>// is same as<br>SomeContainerWithMoveDisabled cmd3(static_cast&lt;SomeContainerWithMoveDisabled&amp;&amp;&gt;(cmd));<br><br>// Now compiler looks for<br>// SomeContainerWithMoveDisabled(SomeContainerWithMoveDisabled&amp;&amp;)<br>// which is not available, but<br>// SomeContainerWithMoveDisabled(const SomeContainerWithMoveDisabled&amp;)<br>// is available, and r-values can bind to const l-value refs.<br></pre><p>So the copy constructor runs. A million ints get deep copid. No warning, no error, nothing.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3813200e574b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Move Constructor That Wasn’t There]]></title>
            <link>https://hksoni.medium.com/the-move-constructor-that-wasnt-there-8cf96e940055?source=rss-9be79c07dba------2</link>
            <guid isPermaLink="false">https://medium.com/p/8cf96e940055</guid>
            <category><![CDATA[c-plus-plus-language]]></category>
            <dc:creator><![CDATA[Harish Kant Soni]]></dc:creator>
            <pubDate>Thu, 24 Sep 2026 06:45:24 GMT</pubDate>
            <atom:updated>2026-09-24T06:45:24.481Z</atom:updated>
            <content:encoded><![CDATA[<p>For a long time I carried around a comfortable little belief: if you don’t write a copy or move constructor yourself, the compiler writes one for you. Done. Nothing to think about.</p><p>I used to think that the compiler generate copy and move ctor if we do not explicitely declare them or delete them. However, that isn’t the case. In this article, I’ll share what I’ve recently learned about move constructors.<br>A move constructor is generated only if all of the following conditions are satisfied:</p><ul><li>No copy operations are declared in the class.</li><li>No move operations are declared in the class.</li><li>No destructor is declared in the class.</li></ul><p>Let me explain with example:</p><pre>struct Point{<br>    int x=0;<br>    int y=0;<br>};<br><br>int main(){<br>    Point p1{1,2};<br>    Point p2 = p2;<br>    Point p3 = move(p1);<br>    return 0;<br>}</pre><p>This works as expected, compiler generate copy and move ctor. However:</p><pre>struct Point{<br>    int x = 0;<br>    int y = 0;<br>    Point(int x,int y):x(x),y(y){}<br>    Point(Point&amp; other){<br>        this-&gt;x = -other.x;<br>        this-&gt;y = -other.y;<br>    }<br>};<br><br>int main(){<br>    Point p{1,2};<br>    Point p2 = p;<br>    Point p3(move(p));<br>    return 0;<br>}</pre><p>This code gives a compilation error at line Point p3(move(p));, as there is no matching constructor. The reason is that since we&#39;ve added a copy constructor, the compiler will not generate the default move constructor.</p><p>You might say we should declare other as const Point&amp; in the copy constructor, and you&#39;d be right. I didn&#39;t write it that way explicitly, because doing so would allow Point p3(move(p)); to compile—not because the compiler would generate a move constructor, but because the r-value reference generated by move(p) can bind to the const l-value reference const Point&amp; other.</p><pre>struct Point{<br>    int x = 0;<br>    int y = 0;<br>    Point(int x,int y):x(x),y(y){}<br>    Point(const Point&amp; other){<br>        this-&gt;x = -other.x;<br>        this-&gt;y = -other.y;<br>    }<br>};<br><br>int main(){<br>    Point p{1,2};<br>    Point p2 = p;<br>    Point p3(move(p));<br>    return 0;<br>}</pre><p>This code compiles not because the compiler has generated a move constructor, but because Point p3(move(p)); calls the copy constructor, for the reason stated above.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8cf96e940055" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[My pipeline got a subagent team — and got faster]]></title>
            <link>https://hksoni.medium.com/my-pipeline-got-a-subagent-team-and-got-faster-38551b198464?source=rss-9be79c07dba------2</link>
            <guid isPermaLink="false">https://medium.com/p/38551b198464</guid>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[claude-subagent]]></category>
            <dc:creator><![CDATA[Harish Kant Soni]]></dc:creator>
            <pubDate>Mon, 21 Sep 2026 16:06:33 GMT</pubDate>
            <atom:updated>2026-09-21T16:06:33.802Z</atom:updated>
            <content:encoded><![CDATA[<p>I’ve got a little repo that turns a quote into a motivational video. Repo’s here: <a href="https://github.com/harishkantsoni/video_generator">github.com/harishkantsoni/video_generator</a>. I use it to post shorts on YouTube: <a href="https://www.youtube.com/@dailypositivity-eng/shorts">@dailypositivity-eng</a>.</p><p><strong>What it does:</strong></p><ul><li>You give it a seed quote (e.g. <em>“Consistency wins hard work”</em>), a list of languages, some background images, and some music</li><li>It writes a ~60 second story that builds up to that quote</li><li>Generates narration with Gemini TTS</li><li>Bakes it all into a finished video with subtitles</li></ul><p><strong>The problem:</strong></p><ul><li>One Claude agent used to do the <em>entire</em> thing itself, for every language</li><li>Write the script → wait for audio → build the video → verify it → repeat for the next language</li><li>All serial. Five languages meant five times the waiting.</li></ul><p><strong>What I changed:</strong></p><ul><li>Split the work into two subagents: <a href="https://github.com/harishkantsoni/video_generator/blob/master/.claude/agents/speech-writer.md">speech-writer</a> and <a href="https://github.com/harishkantsoni/video_generator/blob/master/.claude/agents/video-builder.md">video-builder</a></li><li>Each language now gets its own pair of these agents</li><li>All of them run in parallel, not one after another</li><li>My main agent stopped doing the work itself and started delegating instead — more “lead handing out tasks and tracking status,” less “one person doing everything”</li></ul><p><strong>The result:</strong></p><ul><li>Noticeably faster, especially as I add more languages</li><li>Adding a language used to mean more waiting; now it just means one more pair of agents joining in</li><li>Worth trying anywhere your workflow is “same steps, repeated per item” — languages, regions, whatever your N copies are</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=38551b198464" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Templates in C++ : part-2]]></title>
            <link>https://hksoni.medium.com/templates-in-c-part-2-1689e96eabf3?source=rss-9be79c07dba------2</link>
            <guid isPermaLink="false">https://medium.com/p/1689e96eabf3</guid>
            <category><![CDATA[c-plus-plus-language]]></category>
            <dc:creator><![CDATA[Harish Kant Soni]]></dc:creator>
            <pubDate>Sun, 27 Apr 2025 17:38:37 GMT</pubDate>
            <atom:updated>2025-04-27T17:38:37.886Z</atom:updated>
            <content:encoded><![CDATA[<h3>Templates in C++ : part-2</h3><p>A template is instantiated in following 4 cases:</p><ol><li>When you call the function template</li><li>When you create an explicit specialization</li><li>When you create a pointer to a function template</li><li>When you explicitly instantiate a function template</li></ol><p>These are explained in the example below :</p><pre>#include &lt;iostream&gt;<br><br>template &lt;typename T&gt;<br>T Max(T a, T b) {<br>    return (a &gt; b) ? a : b;<br>}<br><br>// 2. explicit specialization<br>template&lt;&gt;<br>int Max&lt;int&gt;(int a, int b) { <br>    return (a &gt; b) ? a : b;<br>}<br><br>// 4. Explicit instantiation<br>template short Max(short, short);<br><br>int main() {<br>     // 1. calling function template<br>    Max(3,5);<br><br>    // 3. pointer to function template<br>    double (*pfn)(double, double) = Max;<br><br>    // 3. another way of  pointer to function template<br>    auto pfn2 = Max&lt;char&gt;;<br>    return 0;<br>}</pre><p><strong>Explicit Instantiation</strong>: A technique to manually trigger the instantiation of a template. It allows instantiation of a template for specific types in a separate translation unit. Requires an explicit instantiation directive through template keyword and must be specified globally in a .cpp file. There are possible ways to do explicit instantiation in the context of above example:</p><pre>template short Max(short, short);<br>template short Max&lt;short&gt;(short, short);<br>template short Max&lt;&gt;(short, short);</pre><p><strong>Q</strong>. Why do we need explicit instantiation?</p><p><strong>A</strong>. To understand it, we need to understand how templates get compiled. Let’s take an example:</p><p>calc.h is template header only library</p><pre>// calc.h<br>template&lt;typename T&gt;<br>T Sum(T a, T b){<br>    return a + b;<br>}</pre><pre>// main.cpp<br>#include &quot;calc.h&quot;<br>#include &lt;iostream&gt;<br>int main() {<br>    std::cout&lt;&lt;Sum(2,3)&lt;&lt;std::endl;<br>    return 0;<br>}</pre><p>compile these file : g++ -g main.cpp -o main , it works as expected.</p><p>Let’s now try to break calc.h into two files : calc.h and calc.cpp as shown:</p><pre>// calc.h<br>template&lt;typename T&gt;<br>T Sum(T a, T b);</pre><pre>// calc.cpp<br>#include &quot;calc.h&quot;<br><br>template&lt;typename T&gt;<br>T Sum(T a, T b) {<br>    return a + b;<br>}</pre><pre>// main.cpp<br>#include &quot;calc.h&quot;<br>#include &lt;iostream&gt;<br>int main() {<br>    std::cout&lt;&lt;Sum(2,3)&lt;&lt;std::endl;<br>    return 0;<br>}</pre><p>Let’s try to compile main : g++ -g main.cpp -o main, we get error undefined reference to `int Sum&lt;int&gt;(int, int)’</p><p>The reason is definition of int Sum&lt;int&gt;(int, int) is in calc.cpp which we ignored in above compilation. One trivial solution is to include calc.cpp in main.cpp, but we will not discuss about it as it same previous case where we only had calc.h file.</p><p>If you were a library developer of calc, you would provide declarations in calc.h and compiled binary containing definitions in libcalc.a or libcalc.so . To simulate it, we will compile definitions in calc.o and use it while linking main binary.</p><p>Run: g++ -g -c calc.cpp , this would generate calc.o binary. If you run nm -C calc.o , you wouldn’t find demangled name of Sum function for any type. This shows that calc.o does not contain definition of Sum. If we try to link it with main, it will give linking errors.</p><p>To fix this, we will need explicit instantiation of Sum in calc.cpp file like this:</p><pre>// calc.cpp<br>#include &quot;calc.h&quot;<br><br>template&lt;typename T&gt;<br>T Sum(T a, T b) {<br>    return a + b;<br>}<br><br>template int Sum(int, int);</pre><p>Run: g++ -g -c calc.cpp , this would generate calc.o binary. If you run nm -C calc.o , it would show 0000000000000000 W int Sum&lt;int&gt;(int, int). This means that calc.o has definition for Sum if T = int. This can be linked with main now. So final code looks like this:</p><pre>// calc.h<br>template&lt;typename T&gt;<br>T Sum(T a, T b);<br>// ***************************************<br><br><br>// calc.cpp<br>#include &quot;calc.h&quot;<br><br>template&lt;typename T&gt;<br>T Sum(T a, T b) {<br>    return a + b;<br>}<br><br>template int Sum(int, int);<br>// *************************************<br><br><br>// main.cpp<br>#include &quot;calc.h&quot;<br>#include &lt;iostream&gt;<br>int main() {<br>    std::cout&lt;&lt;Sum(2,3)&lt;&lt;std::endl;<br>    return 0;<br>}</pre><p>Run these commands :</p><p>g++ -g -c calc.cpp — &gt; this generates calc.o object file</p><p>g++ -g main.cpp calc.o -o main — -&gt; this generates main binary</p><p>And everything works fine. However, if you try Sum(2.9, 5.6) in main.cpp , you will get error because there is not explicit instantiation of Sum for double.</p><p>In such cases, you would need to provide explicit instantiation of all possible types which user of your calc library may use. Like this:</p><pre>// calc.cpp<br>#include &quot;calc.h&quot;<br><br>template&lt;typename T&gt;<br>T Sum(T a, T b) {<br>    return a + b;<br>}<br><br>template int Sum(int, int);<br>template double Sum(double, double);<br>template float Sum(float, float);<br>template long double Sum(long double, long double);<br>template short Sum(short, short);</pre><p>This way you are able to hide implementation of Sum. Because you only give user calc.h header and calc.o binary and not calc.cpp. However, you are also limiting your library users with the limited types with Sum template function and it is not completely generic now.</p><p>This was one use case of explicit instantiation.</p><p><strong>Explicit instantiation is also helps in reducing compilation time</strong>: Suppose you use header only template library in your code. Like our old calc.h</p><pre>// calc.h<br>template&lt;typename T&gt;<br>T Sum(T a, T b){<br>    return a + b;<br>}</pre><p>If you include calc.h in multiple translational units and all of them instantiate Sum with T=int, all of these translational units will compile same Sum function and will contain same definition of Sum function. This will increase compilation time and all compiled translational units will contain duplicate copies of same Sum function. However, only one copy will be retained after linking. But increase compilation time is still a problem.</p><h3>Template Compilation Model</h3><p>Template compilation model defines how the templates are instantiated, compiled and linked. There are two compilation models:</p><p><strong>Inclusion Compilation Model</strong>: We have been using this model till now. In this model, templates are defined and implemented in header files. These header files are included wherever the templates are required. This causes the compiler to instantiate the template for a specific type when it is used. This leads to simpler implementation because the entire template is defined in a header file. However, when this template is used in different translational units, this leads to multiple instantiation for the same type. Thus it increases compilation time and may lead template bloat.</p><p><strong>Separate Compilation Model</strong>: This is very similar to how we implement function and classes. Templates are declared in a header file, but the definitions are provided in source files. The definitions must be proceeded by the export keyword. It was removed from C++11 due to implementation complexities. Now to use separate compilation model, we need to explicitly instantiate the template in source files. We demonstrated this in previous examples.</p><h3>Extern Templates:</h3><p>Let’s have four files as mentioned below :</p><pre>// utils.h<br>template&lt;typename T&gt;<br>T Max(T a, T b) {<br>    return (a &gt; b) ? a : b;<br>}<br>// *********************************<br><br><br>// foo.cpp<br>#include &quot;utils.h&quot;<br>void foo(){<br>    Max(1,2);<br>}<br>// **********************************<br><br><br><br>// bar.cpp<br>#include &quot;utils.h&quot;<br>void bar(){<br>    Max(1,2);<br>}<br>// *******************************<br><br><br>// main.cpp<br>#include &quot;utils.h&quot;<br>int main(){<br>    Max(1,2);<br>    return 0;<br>}</pre><p>If we create foo.o from foo.cpp, bar.o from bar.cpp and main.o from main.cpp, each object file is going to have identical definition of int Max&lt;int&gt;(int, int) . This is redundant as it increases compile time. When we link all these object files into a single binary, compiler will keep only one copy of int Max&lt;int&gt;(int, int). This is not violation of ODR(One definition Rule) as these are special functions.</p><p>To avoid multiple instantiation of Max for int types, we can use extern templates. Like this :</p><pre>// utils.h<br>template&lt;typename T&gt;<br>T Max(T a, T b) {<br>    return (a &gt; b) ? a : b;<br>}<br><br>extern template int Max(int a, int b);</pre><p>When we build foo.o, bar.o, main.o, the compiler will not instantiate Max for int types. Although, it can instantiate Max for other types. If we try to create a single binary from foo.o, bar.o, main.o , we will get linker errors. To get rid of this linker error, we need to provide an explicit instantiation in one of the source files. It can be foo.cpp, bar.cpp or main.cpp . We are doing that in main.cpp .</p><pre>// utils.h<br>template&lt;typename T&gt;<br>T Max(T a, T b) {<br>    return (a &gt; b) ? a : b;<br>}<br>extern template int Max(int a, int b);<br>// *********************************<br><br>// foo.cpp<br>#include &quot;utils.h&quot;<br>void foo(){<br>    Max(1,2);<br>}<br>// **********************************<br><br>// bar.cpp<br>#include &quot;utils.h&quot;<br>void bar(){<br>    Max(1,2);<br>}<br>// *******************************<br><br>// main.cpp<br>#include &quot;utils.h&quot;<br>template int Max(int, int); <br>int main(){<br>    Max(1,2);<br>    return 0;<br>}</pre><p>This way we will get rid of the linker error.</p><p>This is how we can leverage extern template to avoid multiple instantiation of template for same type.</p><h3>Static Variable In Function Templates</h3><ul><li>Function templates can also contain static variables.</li><li>Each call to the function template with a different argument type will trigger new instantiation of function template.</li><li>Each instantiation will have its own copy of the static variable.</li><li>The value of the static variable is not shared between the different instantiations of the template.</li></ul><pre>#include &lt;iostream&gt;<br><br>template &lt;typename T&gt;<br>void Print(T a){<br>    static int counter = 0;<br>    std::cout &lt;&lt; &quot;Counter : &quot; &lt;&lt; ++counter ;<br>    std::cout &lt;&lt; &quot;, value : &quot; &lt;&lt; a &lt;&lt;std::endl;<br>}<br><br>int main(){<br>    Print(5);<br>    Print(10);<br>    Print(15);<br>    std::cout &lt;&lt; &quot;------------------------&quot; &lt;&lt; std::endl;<br>    Print(2.3);<br>    Print(3.4);<br>    return 0;<br>}</pre><p>The above code outputs:</p><pre>Counter : 1, value : 5<br>Counter : 2, value : 10<br>Counter : 3, value : 15<br>------------------------<br>Counter : 1, value : 2.3<br>Counter : 2, value : 3.4</pre><p>There are two instantiations of Print happening for int and double types. Both of these instantiations will have separate copy of static int counter variable.</p><p>Reference : <a href="https://www.udemy.com/course/modcpptemplates">https://www.udemy.com/course/modcpptemplates</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1689e96eabf3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Templates in C++ : Pa]]></title>
            <link>https://hksoni.medium.com/templates-in-c-pa-a1d8354edcfd?source=rss-9be79c07dba------2</link>
            <guid isPermaLink="false">https://medium.com/p/a1d8354edcfd</guid>
            <category><![CDATA[cplusplus]]></category>
            <dc:creator><![CDATA[Harish Kant Soni]]></dc:creator>
            <pubDate>Sat, 26 Apr 2025 18:16:26 GMT</pubDate>
            <atom:updated>2025-05-12T12:12:58.708Z</atom:updated>
            <content:encoded><![CDATA[<h3>Templates in C++ : Part -1</h3><p>A template is a blueprint for a function or a class. It allows a programmer to write code without explicitly specifying the type. Templates forms the basis of generic programming in C++. Thought templates, we can implement generic algorithms &amp; classes that can operate on any kind of type.</p><p>Syntax :</p><p>template &lt;typename TypeName&gt;, TypeName is placeholder for actual type. It is automatically replaced by compiler during compilation.</p><pre>#include &lt;iostream&gt;<br><br>template &lt;typename T&gt;<br>T Max(T a, T b) {<br>    return (a &gt; b) ? a : b;<br>}<br>int main(){<br>    auto result = Max(5, 10);<br>    std::cout &lt;&lt; &quot;Max of 5 and 10 is: &quot; &lt;&lt; result &lt;&lt; std::endl;<br><br>    auto result2 = Max(5.5, 10.2);<br>    std::cout &lt;&lt; &quot;Max of 5.5 and 10.2 is: &quot; &lt;&lt; result2 &lt;&lt; std::endl;<br>    return 0;<br>}</pre><p>above code works with any type which can be compared with &gt; operator. During compilation, the compiler will instantiate this Max template for int and double.</p><p>To verify this, compile C++ code on Linux using -g flag and use nm command to read symbol table.</p><p>g++ -g your_code.cpp -o your_code</p><p>nm -C your_code</p><p>You should see this entry :</p><p>000000000000128e W double Max&lt;double&gt;(double, double)<br>000000000000126e W int Max&lt;int&gt;(int, int)</p><p>This shows that the compiler created two function from the template for int and double.</p><p>Template code in compiled in 2 phases.</p><p>In the first phase, the compiler examines the template for syntax errors. The compiler ignore the templates parameters and any code that does not depend on templates is checked.</p><p>The second phase is the instantiation phase where the template code is checked again but this time with the template types.</p><p>Due to two-phase translation, the compiler should have access to the definition of the template. When the instantiation of the template is triggered, the compiler must examine the definition.</p><p>The compiler does not perform any type conversion while deducing the template types.</p><pre>#include &lt;iostream&gt;<br><br>template &lt;typename T&gt;<br>T Max(T a, T b) {<br>    return (a &gt; b) ? a : b;<br>}<br><br>int main(){<br>    auto result = Max(5, 10.2);<br>    std::cout &lt;&lt; &quot;Max of 5 and 10.2 is: &quot; &lt;&lt; result &lt;&lt; std::endl;<br>    return 0;<br>}</pre><p>Above code generates error template argument deduction/substitution failed:</p><p><strong>Explicit template arguments:</strong></p><p>There are 2 ways to solve above error. Either we can solve above problem by converting both argument to same type using static_cast</p><pre>#include &lt;iostream&gt;<br><br>template &lt;typename T&gt;<br>T Max(T a, T b) {<br>    return (a &gt; b) ? a : b;<br>}<br><br>int main(){<br>    auto result = Max(static_cast&lt;double&gt;(5), 10.2);<br>    std::cout &lt;&lt; &quot;Max of 5 and 10.2 is: &quot; &lt;&lt; result &lt;&lt; std::endl;<br>    return 0;<br>}</pre><p>Another way is to explicitly specifying the type of template parameter. When we do it, it will override compiler’s type deduction.</p><pre>#include &lt;iostream&gt;<br><br>template &lt;typename T&gt;<br>T Max(T a, T b) {<br>    return (a &gt; b) ? a : b;<br>}<br><br>int main(){<br>    auto result = Max&lt;double&gt;(5, 10.2);<br>    std::cout &lt;&lt; &quot;Max of 5 and 10.2 is: &quot; &lt;&lt; result &lt;&lt; std::endl;<br>    return 0;<br>}</pre><p>Let’s look at one more example:</p><pre>#include &lt;iostream&gt;<br><br>template &lt;typename T1, typename T2&gt;<br>void Product(T1 a, T2 b) {<br>    std::cout &lt;&lt; &quot;Product: &quot; &lt;&lt; a * b &lt;&lt; std::endl;<br>}<br><br>int main(){<br>    Product(5, 3.13);<br>    return 0;<br>}<br>// output:<br>// Product: 15.65</pre><p>It works fine, let’s try to return value from Product</p><pre>#include &lt;iostream&gt;<br><br>template &lt;typename T1, typename T2&gt;<br>T1 Product(T1 a, T2 b) {<br>    return a * b;<br>}<br><br>int main(){<br>    std::cout &lt;&lt; &quot;Product : &quot; &lt;&lt; Product(5, 3.13) &lt;&lt; std::endl;<br>    return 0;<br>}<br>//output :<br>// Product : 15</pre><p>Here product of 5 x 3.13 = 15, which is not correct. The problem is first argument to the Product is int which causes T1 to be deduced as int. It cause return value to be integer.</p><p>Below code works fine, because return type it T2.</p><pre>#include &lt;iostream&gt;<br><br>template &lt;typename T1, typename T2&gt;<br>T2 Product(T1 a, T2 b) {<br>    return a * b;<br>}<br><br>int main(){<br>    std::cout &lt;&lt; &quot;Product : &quot; &lt;&lt; Product(5, 3.13) &lt;&lt; std::endl;<br>    return 0;<br>}<br>//output :<br>// Product : 15.65</pre><p>Here we should not have return type as either T1 or T2, because this could lead to loss of information as shown in previous example. There are multiple ways to solve this problem:</p><p>One way to fix this problem is to introduce return type TResult and use explicit type specification :</p><pre>#include &lt;iostream&gt;<br><br>template &lt;typename T1, typename T2, typename TResult&gt;<br>TResult Product(T1 a, T2 b) {<br>    return a * b;<br>}<br><br>int main(){<br>    auto result = Product&lt;int, double, double&gt;(5, 3.13);<br>    std::cout &lt;&lt; &quot;The product is: &quot; &lt;&lt; result &lt;&lt; std::endl;<br>    return 0;<br>}<br>// ouput<br>// The product is: 15.65</pre><p>Here we have to specify the type of argument to function Product along with return type.</p><p>We can explicitly specify type of TResult and let compiler deduce type of T1 and T2 this way:</p><pre>#include &lt;iostream&gt;<br><br>template &lt;typename TResult, typename T1, typename T2&gt;<br>TResult Product(T1 a, T2 b) {<br>    return a * b;<br>}<br><br>int main(){<br>    auto result = Product&lt;double&gt;(5, 3.13);<br>    std::cout &lt;&lt; &quot;The product is: &quot; &lt;&lt; result &lt;&lt; std::endl;<br>    return 0;<br>}<br>// ouput<br>// The product is: 15.65</pre><p>In C++11, we can make use of auto and decltype to avoid use to third template argument TResult.</p><pre>// works in C++11<br>#include &lt;iostream&gt;<br>template &lt;typename T1, typename T2&gt;<br>auto Product(T1 a, T2 b)-&gt; decltype(a * b) {<br>    return a * b;<br>}<br><br>int main(){<br>    auto result = Product(5, 3.13);<br>    std::cout &lt;&lt; &quot;The product is: &quot; &lt;&lt; result &lt;&lt; std::endl;<br>    return 0;<br>}<br>// output<br>// The product is: 15.65</pre><p>In C++14, we do not need to use -&gt; decltype(a * b), compiler will figure out return type automaticaly.</p><pre>// works in C++14, but not in C++11<br>#include &lt;iostream&gt;<br>template &lt;typename T1, typename T2&gt;<br>auto Product(T1 a, T2 b) {<br>    return a * b;<br>}<br><br>int main(){<br>    auto result = Product(5, 3.13);<br>    std::cout &lt;&lt; &quot;The product is: &quot; &lt;&lt; result &lt;&lt; std::endl;<br>    return 0;<br>}<br>// output<br>// The product is: 15.65</pre><p>We can also use type traits added in C++11 to find out return type. std::common_type_t&lt;T1,T2&gt; will return a type which is common in T1 and T2. It will return double in our case as double is most common in int and double.</p><pre>#include &lt;iostream&gt;<br>#include &lt;type_traits&gt;<br><br>template &lt;typename T1, typename T2&gt;<br>std::common_type_t&lt;T1,T2&gt; Product(T1 a, T2 b) {<br>    return a * b;<br>}<br><br>int main(){<br>    auto result = Product(5, 3.13);<br>    std::cout &lt;&lt; &quot;The product is: &quot; &lt;&lt; result &lt;&lt; std::endl;<br>    return 0;<br>}<br>// output<br>// The product is: 15.65</pre><p>We can also use default type in this case. If we provide a default type to a template argument, that will be used when explicit type is not provided.</p><pre>#include &lt;iostream&gt;<br><br>template &lt;typename T1, typename T2, typename TResult = double&gt;<br>TResult Product(T1 a, T2 b) {<br>    return a * b;<br>}<br><br>int main(){<br>    auto result = Product(5, 3.13);<br>    std::cout &lt;&lt; &quot;The product is: &quot; &lt;&lt; result &lt;&lt; std::endl;<br>    return 0;<br>}<br>// output<br>// The product is: 15.65</pre><p>We can use one more variation of it, we can provide default template type using type traits, as shown:</p><pre>#include &lt;iostream&gt;<br>#include &lt;type_traits&gt;<br><br>template &lt;typename T1, typename T2, typename TResult = std::common_type_t&lt;T1, T2&gt;&gt;<br>TResult Product(T1 a, T2 b) {<br>    return a * b;<br>}<br><br>int main(){<br>    auto result = Product(5, 3.13);<br>    std::cout &lt;&lt; &quot;The product is: &quot; &lt;&lt; result &lt;&lt; std::endl;<br>    return 0;<br>}</pre><h3>Argument Conversion:</h3><p>During template instantiation, no type conversion is performed. However, if template arguments are passed by value, limited(trivial) type conversion is allowed.</p><p>Any cv-qualifiers on the arguments are ignored. Passing a constant identifier by value removes its const-ness. This means the same instantiation will work for both const and non-const identifiers.</p><p>Array and function decay to pointers. Passing an array and a function will not trigger separate instantiation of the template.</p><pre>#include &lt;iostream&gt;<br><br>template &lt;typename T&gt;<br>void Foo(T a) {<br>    std::cout&lt;&lt; typeid(T).name() &lt;&lt; std::endl;<br>}<br><br>int main(){<br>    Foo(3u);<br>    Foo(3);<br>    Foo(&#39;a&#39;);<br>    return 0;<br>}</pre><p>In the example above, Foo is instantiated 3 times. It gives output :</p><pre>j<br>i<br>c</pre><p>j -&gt; unsigned int</p><p>i -&gt; int</p><p>c -&gt; char</p><p>we can check functions instantiated using nm command.</p><pre>0000000000001253 W void Foo&lt;char&gt;(char)<br>000000000000120e W void Foo&lt;int&gt;(int)<br>00000000000011c9 W void Foo&lt;unsigned int&gt;(unsigned int)</pre><p>Let’s see one more example</p><pre>#include &lt;iostream&gt;<br><br>template &lt;typename T&gt;<br>void Foo(T a) {<br>    std::cout&lt;&lt; typeid(T).name() &lt;&lt; std::endl;<br>}<br><br>int main(){<br>    Foo(3u);<br>    Foo(3);<br>    Foo(&#39;a&#39;);<br><br>    const int x = 3;<br>    Foo(x);<br>    return 0;<br>}</pre><p>In this example, const ness x will removed and function instantiated by Foo(3) will be used again by Foo(x).</p><pre>#include &lt;iostream&gt;<br><br>template &lt;typename T&gt;<br>void Foo(T a) {<br>    std::cout&lt;&lt; typeid(T).name() &lt;&lt; std::endl;<br>}<br><br>int main(){<br>    int y = 10;<br>    Foo(&amp;y);<br>    <br>    int arr[5];<br>    Foo(arr);<br>    return 0;<br>}</pre><p>Above code outputs :</p><pre>Pi<br>Pi</pre><p>Pi -&gt; Pointer to integer</p><p>In above code array decays to a pointer to an integer, that’s why compiler will use same instantiation created by Foo(&amp;y) for Foo(arr).</p><pre>#include &lt;iostream&gt;<br><br>template &lt;typename T&gt;<br>void Foo(T a) {<br>    std::cout&lt;&lt; typeid(T).name() &lt;&lt; std::endl;<br>}<br><br>void f1(){}<br>void f2(){}<br><br>int main(){<br>    Foo(f1);<br>    Foo(f2);<br>    return 0;<br>}</pre><p>In above example, name of the function will decay to a pointer and type of that pointer will represent signature of the function. Since signature of f1 and f2 is same, only one template instantiation will be performed. This code outputs :</p><pre>PFvvE<br>PFvvE</pre><p>nm command shows :</p><pre>00000000000011df W void Foo&lt;void (*)()&gt;(void (*)())</pre><h3>Templates with Specifiers:</h3><p><strong>static: </strong>using static on a template is not of much use. Because every translational unit of code will get its own copy of static function which can be invoked only from that translational unit. Since out template function is in a header file, multiple copies of that static function will be created in translational units instantiating the template. The linker will link to the local copy inside the translational unit.</p><p><strong>inline: </strong>Using inline on templates is not required. Modern compilers are quite intelligent. They can inline function when instantiated if needed.</p><p><strong>constexpr:</strong> It is useful in case this function can be evaluated at compile time.</p><h3>Non-Type Template Parameters:</h3><p>Till now we only used type parameter in templates, but we can also use no-type parameters in templates. But these has to an integral type.</p><pre>#include &lt;iostream&gt;<br><br>template&lt;int value&gt;<br>void Print(){<br>    std::cout &lt;&lt; &quot;value: &quot; &lt;&lt; value &lt;&lt; std::endl;<br>}<br><br>int main(){<br>    Print&lt;5&gt;();<br>    return 0;<br>}<br>// output<br>// value: 5</pre><p>There are a couple of restriction that apply to Non-type template parameters.</p><ul><li>Non-type parameter can only be on integral type. It can be following type: char, short, int , long, enum, nullptr etc.</li><li>Any value used as Non-type parameter should be a compile time expression.</li><li>String literals cannot be used.</li></ul><pre>#include &lt;iostream&gt;<br><br>template&lt;int value&gt;<br>void Print(){<br>    std::cout &lt;&lt; &quot;value: &quot; &lt;&lt; value &lt;&lt; std::endl;<br>}<br><br>int main(){<br>    int i = 5;<br>    Print&lt;i&gt;();<br>    return 0;<br>}</pre><p>Above code will not compile because in Print&lt;i&gt;(), i is not a compile time expression.</p><pre>#include &lt;iostream&gt;<br><br>template&lt;int value&gt;<br>void Print(){<br>    std::cout &lt;&lt; &quot;value: &quot; &lt;&lt; value &lt;&lt; std::endl;<br>}<br><br>int main(){<br>    auto p = &quot;Hello&quot;;<br>    Print&lt;p&gt;();<br><br>    Print&lt;&quot;Hello&quot;&gt;();<br>    <br>    return 0;<br>}</pre><p>Above code will not compile, because <em>string literals and pointer to string literals are not allowed</em> as non-type parameters. Although, pointer can be used as non-type parameters, but pointers to string literals can not be.</p><p>Non-type template parameters become part of function signature.</p><p>From C++17 onwards, you can use auto with non-type parameters. As shown in this example:</p><pre>#include &lt;iostream&gt;<br><br>template&lt;auto value&gt;<br>void Print(){<br>    std::cout &lt;&lt; &quot;value: &quot; &lt;&lt; value &lt;&lt; std::endl;<br>}<br><br>int main(){<br>    Print&lt;3u&gt;();<br>    Print&lt;10&gt;();<br>    Print&lt;20&gt;();<br>    Print&lt;&#39;a&#39;&gt;();<br>    return 0;<br>}</pre><p>One point to note here, is the Print() will instantiate when it is invoked with some non-type arguments. If you invoke the function with different augments for non-type template parameters, each different argument will cause the compiler to instantiate a Print&lt;&gt;() for that particular argument.</p><p>If we run nm -C on executable obtained by compiling above source code, we can see that total four Print&lt;&gt;() are instantiated.</p><pre>00000000000012b5 W void Print&lt;(char)97&gt;()<br>000000000000122f W void Print&lt;10&gt;()<br>0000000000001272 W void Print&lt;20&gt;()<br>00000000000011ec W void Print&lt;3u&gt;()</pre><p>Non-type template parameters are frequently used with arrays.</p><pre>#include &lt;iostream&gt;<br>#include &lt;limits&gt;<br><br>template &lt;typename T&gt;<br>size_t Find(const T* arr, size_t size, const T&amp; value) {<br>    for (size_t i = 0; i &lt; size; ++i) {<br>        if (arr[i] == value) {<br>            return i;<br>        }<br>    }<br>    return std::numeric_limits&lt;size_t&gt;::max();<br>}<br><br>int main(){<br>    int arr[] = {1, 2, 3, 4, 5};<br>    size_t size = sizeof(arr) / sizeof(arr[0]);<br>    int value = 3;<br>    size_t index = Find(arr, size, value);<br>    if (index != std::numeric_limits&lt;size_t&gt;::max()) {<br>        std::cout &lt;&lt; &quot;Value &quot; &lt;&lt; value &lt;&lt; &quot; found at index &quot; &lt;&lt; index &lt;&lt; std::endl;<br>    } else {<br>        std::cout &lt;&lt; &quot;Value &quot; &lt;&lt; value &lt;&lt; &quot; not found&quot; &lt;&lt; std::endl;<br>    }<br>    return 0;<br>}<br>// *********output********<br>// Value 3 found at index 2</pre><p>In above example, the programmer has to explicitly pass size of array. We need to pass size, because when array is passed to a function, it decays into a pointer and the information about the size is lost. But this templates if we pass an array by reference, then we don’t have to explicitly pass the size. The size can be automictically passed as a non-type template argument.</p><p>For your reference, this is how an array is passed by reference :</p><pre>void foo(int (&amp;myArray)[100])<br>{<br>}<br><br>int main()<br>{<br>    int a[100];<br>    foo(a);<br>}</pre><p>This is how we can rewrite Find() algorithm for arrays:</p><pre>#include &lt;iostream&gt;<br>#include &lt;limits&gt;<br><br>template &lt;typename T, size_t size&gt;<br>size_t Find(const T(&amp;arr)[size], const T&amp; value) {<br>    for (size_t i = 0; i &lt; size; ++i) {<br>        if (arr[i] == value) {<br>            return i;<br>        }<br>    }<br>    return std::numeric_limits&lt;size_t&gt;::max();<br>}<br><br>int main(){<br>    int arr[] = {1, 2, 3, 4, 5};<br>    int value = 3;<br>    size_t index = Find(arr, value);<br>    if (index != std::numeric_limits&lt;size_t&gt;::max()) {<br>        std::cout &lt;&lt; &quot;Value &quot; &lt;&lt; value &lt;&lt; &quot; found at index &quot; &lt;&lt; index &lt;&lt; std::endl;<br>    } else {<br>        std::cout &lt;&lt; &quot;Value &quot; &lt;&lt; value &lt;&lt; &quot; not found&quot; &lt;&lt; std::endl;<br>    }<br>    return 0;<br>}</pre><h3>Overloading Function templates</h3><p>We have already seen Max() template function to return max of two number. If we want to create Max() template function to return max of three numbers, we need to overload it.</p><pre>#include &lt;iostream&gt;<br><br>template &lt;typename T&gt;<br>T Max(T a, T b) {<br>    std::cout&lt;&lt;__PRETTY_FUNCTION__&lt;&lt;std::endl;<br>    return (a &gt; b) ? a : b;<br>}<br><br>template &lt;typename T&gt;<br>T Max(T a, T b, T c) {<br>    std::cout&lt;&lt;__PRETTY_FUNCTION__&lt;&lt;std::endl;<br>    auto temp = a&gt;b ? a : b;<br>    return (temp &gt; c) ? temp : c;<br>}<br><br>int main(){<br>    auto a = Max(1, 2);<br>    auto b = Max(1, 2, 3);<br>    return 0;<br>}<br>// ********output********<br>// T Max(T, T) [with T = int]<br>// T Max(T, T, T) [with T = int]</pre><p>Let’s try to compare two integers whose pointer we have :</p><pre>#include &lt;iostream&gt;<br><br>template &lt;typename T&gt;<br>T Max(T a, T b) {<br>    std::cout&lt;&lt;__PRETTY_FUNCTION__&lt;&lt;std::endl;<br>    return (a &gt; b) ? a : b;<br>}<br><br>int main(){<br>    int *p1 = new int(10);<br>    int *p2 = new int(20);<br>    std::cout &lt;&lt; Max(p1, p2) &lt;&lt; std::endl;<br><br>    return 0;<br>}<br>// *******output*******<br>// T Max(T, T) [with T = int*]<br>// 0x56267ccd32d0</pre><p>Clearly this is not what we want, we want. We need to cerate overload of Max for pointers.</p><pre>#include &lt;iostream&gt;<br><br>template &lt;typename T&gt;<br>T Max(T a, T b) {<br>    std::cout&lt;&lt;__PRETTY_FUNCTION__&lt;&lt;std::endl;<br>    return (a &gt; b) ? a : b;<br>}<br><br>template &lt;typename T&gt;<br>T Max(T* a, T* b) {<br>    std::cout&lt;&lt;__PRETTY_FUNCTION__&lt;&lt;std::endl;<br>    return (*a &gt; *b) ? *a : *b;<br>}<br><br>int main(){<br>    int *p1 = new int(10);<br>    int *p2 = new int(20);<br>    std::cout &lt;&lt; Max(p1, p2) &lt;&lt; std::endl;<br><br>    return 0;<br>}<br>// **********output*********<br>// T Max(T*, T*) [with T = int]<br>// 20</pre><p>When pointer overloaded template Max was absent, compiler used the existing non pointer version of Max. But now as we have overload of pointer type for Max, this is used. With function templates compiler will try to find the best match.</p><p>Lets try to use Max with strings</p><pre>#include &lt;iostream&gt;<br><br>template &lt;typename T&gt;<br>T Max(T a, T b) {<br>    std::cout&lt;&lt;__PRETTY_FUNCTION__&lt;&lt;std::endl;<br>    return (a &gt; b) ? a : b;<br>}<br><br>template &lt;typename T&gt;<br>T Max(T* a, T* b) {<br>    std::cout&lt;&lt;__PRETTY_FUNCTION__&lt;&lt;std::endl;<br>    return (*a &gt; *b) ? *a : *b;<br>}<br><br>int main(){<br>    char *str1 = new char[]{&quot;C++&quot;};<br>    char *str2 = new char[]{&quot;Java&quot;};<br>    std::cout &lt;&lt; Max(str1, str2) &lt;&lt; std::endl;<br>    return 0;<br>}<br>// *******output********<br>// T Max(T*, T*) [with T = char]<br>// J</pre><p>As str1 and str2 are pointers, the compiler will choose T Max(T* a, T* b) version of Max. But we do not compare strings as we compare number with &gt; operator. We need to use strcmp from cstring library.</p><pre>#include &lt;iostream&gt;<br>#include &lt;cstring&gt;<br><br>template &lt;typename T&gt;<br>T Max(T a, T b) {<br>    std::cout&lt;&lt;__PRETTY_FUNCTION__&lt;&lt;std::endl;<br>    return (a &gt; b) ? a : b;<br>}<br><br>template &lt;typename T&gt;<br>T Max(T* a, T* b) {<br>    std::cout&lt;&lt;__PRETTY_FUNCTION__&lt;&lt;std::endl;<br>    return (*a &gt; *b) ? *a : *b;<br>}<br><br>char* Max(char* a, char* b) {<br>    std::cout&lt;&lt;__PRETTY_FUNCTION__&lt;&lt;std::endl;<br>    return (strcmp(a, b) &gt; 0) ? a : b;<br>}<br><br>int main(){<br>    char *str1 = new char[]{&quot;C++&quot;};<br>    char *str2 = new char[]{&quot;Java&quot;};<br>    std::cout &lt;&lt; Max(str1, str2) &lt;&lt; std::endl;<br>    return 0;<br>}<br>// *********output**********<br>// char* Max(char*, char*)<br>// Java</pre><p>Whenever compiler encounters a call to a function, it will always try to look for the most specialized function. That is why in this case char* Max(char* a, char* b) will be used as this is the most specialized. This example show that function templates can also overload with non-template functions.</p><h3>Explicit Specialization</h3><p>Explicit specialization is used when a function or class template may not give correct semantics for a particular type. We then implement the template separately fo that type, and this is called explicit specialization. You can specialize classes, function and class-methods. The specialization is not a template and must be treated like a normal function/class. If we specialize a function template, the its definition cannot appear in a header file because that will violate one definition rule. When you specialize a function or a class template, the the specialization must begin with an empty template parameter list. Like this:template&lt;&gt; void F(&lt;type&gt;)</p><pre>#include &lt;iostream&gt;<br>#include &lt;cstring&gt;<br><br>template &lt;typename T&gt;<br>T Max(T a, T b) {<br>    std::cout&lt;&lt;__PRETTY_FUNCTION__&lt;&lt;std::endl;<br>    return (a &gt; b) ? a : b;<br>}<br><br>template &lt;&gt;<br>char* Max(char *a, char *b) {<br>    std::cout&lt;&lt;__PRETTY_FUNCTION__&lt;&lt;std::endl;<br>    return (strcmp(a, b) &gt; 0) ? a : b;<br>}<br><br><br>int main(){<br>    char *str1 = new char[]{&quot;C++&quot;};<br>    char *str2 = new char[]{&quot;Java&quot;};<br>    std::cout &lt;&lt; Max(str1, str2) &lt;&lt; std::endl;<br>    return 0;<br>}<br>// ****output************<br>// T Max(T, T) [with T = char*]<br>// Java</pre><p>Here char* Max(char *a, char *b) is specialization while T Max(T a, T b) is base template. Before you create a specialization of a template, the base template must exist.</p><pre>#include &lt;iostream&gt;<br>#include &lt;cstring&gt;<br><br>template &lt;typename T&gt;<br>T Max(T a, T b) {<br>    std::cout&lt;&lt;__PRETTY_FUNCTION__&lt;&lt;std::endl;<br>    return (a &gt; b) ? a : b;<br>}<br><br>template &lt;&gt;<br>char* Max(char *a, char *b) {<br>    std::cout&lt;&lt;__PRETTY_FUNCTION__&lt;&lt;std::endl;<br>    return (strcmp(a, b) &gt; 0) ? a : b;<br>}<br><br>char* Max(char *a, char *b) {<br>    std::cout&lt;&lt;&quot;non template version of Max&quot;&lt;&lt;std::endl;<br>    return (strcmp(a, b) &gt; 0) ? a : b;<br>}<br><br><br>int main(){<br>    char *str1 = new char[]{&quot;C++&quot;};<br>    char *str2 = new char[]{&quot;Java&quot;};<br>    std::cout &lt;&lt; Max(str1, str2) &lt;&lt; std::endl;<br>    return 0;<br>}<br>// ***********output**********<br>// non template version of Max<br>// Java</pre><p>Here we have added non template version of Max. In this case, non-template version of Max is called as this is most specialized function.</p><p>We will look at some more examples. Guess the output of this code:</p><pre>#include &lt;iostream&gt;<br>#include &lt;cstring&gt;<br><br>template &lt;typename T&gt;<br>T Max(T a, T b) {<br>    std::cout&lt;&lt;&quot;T Max(T a, T b)&quot;&lt;&lt;std::endl;<br>    return (a &gt; b) ? a : b;<br>}<br><br>template &lt;&gt;<br>char* Max(char *a, char *b) {<br>    std::cout&lt;&lt;&quot;char* Max(char *a, char *b)&quot;&lt;&lt;std::endl;<br>    return (strcmp(a, b) &gt; 0) ? a : b;<br>}<br><br>template &lt;typename T&gt;<br>T* Max(T *a, T *b) {<br>    std::cout&lt;&lt;&quot;T* Max(T *a, T *b)&quot;&lt;&lt;std::endl;<br>    return (*a &gt; *b) ? a : b;<br>}<br><br>int main(){<br>    char *str1 = new char[]{&quot;C++&quot;};<br>    char *str2 = new char[]{&quot;Java&quot;};<br>    std::cout &lt;&lt; Max(str1, str2) &lt;&lt; std::endl;<br>    return 0;<br>}</pre><p>Which function template gets called Max(T a, T b), char* Max(char *a, char *b) or T* Max(T *a, T *b) ?</p><p>The output is :</p><p>T* Max(T *a, T *b)<br>Java</p><p><strong><em>Templates are selected before specialization is considered when matching. Then compiler will choose the most specialized version.</em></strong></p><p>In other words, template specialization does not take part in template overload. There are only two overloads template &lt;typename T&gt; T Max(T a, T b) and template &lt;typename T&gt; T* Max(T *a, T *b) .</p><p>In the case above, template &lt;&gt; char* Max(char *a, char *b) is the specialization of template &lt;typename T&gt; T Max(T a, T b) and not template &lt;typename T&gt; T* Max(T *a, T *b). The compiler will first select a template between template &lt;typename T&gt; T Max(T a, T b) and template &lt;typename T&gt; T* Max(T *a, T *b) . Obviously, here template &lt;typename T&gt; T* Max(T *a, T *b) is better match. The compiler will check if any specialization is available for this template. In our case, no specialization is available for template &lt;typename T&gt; T* Max(T *a, T *b).</p><p>Let’s move template &lt;&gt; char* Max(char *a, char *b) after template &lt;typename T&gt; T* Max(T *a, T *b)</p><pre>#include &lt;iostream&gt;<br>#include &lt;cstring&gt;<br><br>template &lt;typename T&gt;<br>T Max(T a, T b) {<br>    std::cout&lt;&lt;&quot;T Max(T a, T b)&quot;&lt;&lt;std::endl;<br>    return (a &gt; b) ? a : b;<br>}<br><br>template &lt;typename T&gt;<br>T* Max(T *a, T *b) {<br>    std::cout&lt;&lt;&quot;T* Max(T *a, T *b)&quot;&lt;&lt;std::endl;<br>    return (*a &gt; *b) ? a : b;<br>}<br><br>template &lt;&gt;<br>char* Max(char *a, char *b) {<br>    std::cout&lt;&lt;&quot;char* Max(char *a, char *b)&quot;&lt;&lt;std::endl;<br>    return (strcmp(a, b) &gt; 0) ? a : b;<br>}<br><br>int main(){<br>    char *str1 = new char[]{&quot;C++&quot;};<br>    char *str2 = new char[]{&quot;Java&quot;};<br>    std::cout &lt;&lt; Max(str1, str2) &lt;&lt; std::endl;<br>    return 0;<br>}</pre><p>Guess the output !</p><p>The output is :</p><p>char* Max(char *a, char *b)<br>Java</p><p>The reason is now template &lt;&gt; char* Max(char *a, char *b) has become specialization of template &lt;typename T&gt; T* Max(T *a, T *b) .</p><p><strong>Q. If we want to provide an implementation of function template for a specific type, should we use explicit specialization or non-template overload?</strong></p><p>A. In such cases, always prefer non-template over loads. In the above two example, we should have used non-template overload on Max function like this:</p><pre>char* Max(char *a, char *b) {<br>    std::cout&lt;&lt;&quot;char* Max(char *a, char *b)&quot;&lt;&lt;std::endl;<br>    return (strcmp(a, b) &gt; 0) ? a : b;<br>}</pre><p>Please note that it is not an explicit template specialization as it does not start with template&lt;&gt;.</p><p><strong>Exercise</strong>: Write a template specialization of Max function mentioned above for const char* types and use it in main function.</p><pre>#include &lt;iostream&gt;<br>#include &lt;cstring&gt;<br><br>template &lt;typename T&gt;<br>T Max(T a, T b) {<br>    std::cout&lt;&lt;&quot;T Max(T a, T b)&quot;&lt;&lt;std::endl;<br>    return (a &gt; b) ? a : b;<br>}<br><br>template &lt;typename T&gt;<br>T* Max(T *a, T *b) {<br>    std::cout&lt;&lt;&quot;T* Max(T *a, T *b)&quot;&lt;&lt;std::endl;<br>    return (*a &gt; *b) ? a : b;<br>}<br><br>template &lt;&gt;<br>char* Max(char *a, char *b) {<br>    std::cout&lt;&lt;&quot;char* Max(char *a, char *b)&quot;&lt;&lt;std::endl;<br>    return (strcmp(a, b) &gt; 0) ? a : b;<br>}<br><br>template &lt;&gt;<br>const char* Max(const char *a, const char *b) {<br>    std::cout&lt;&lt;&quot;const char* Max(const char *a, const char *b)&quot;&lt;&lt;std::endl;<br>    return (strcmp(a, b) &gt; 0) ? a : b;<br>}<br><br><br>int main(){<br>    char *str1 = new char[]{&quot;C++&quot;};<br>    char *str2 = new char[]{&quot;Java&quot;};<br>    std::cout &lt;&lt; Max(str1, str2) &lt;&lt; std::endl;<br><br>    const char *str3 = new char[]{&quot;C++&quot;};<br>    const char *str4 = new char[]{&quot;Java&quot;};<br>    std::cout &lt;&lt; Max(str3, str4) &lt;&lt; std::endl;<br><br>    return 0;<br>}</pre><p>Output:</p><pre>char* Max(char *a, char *b)<br>Java<br>const char* Max(const char *a, const char *b)<br>Java</pre><p>What’s the output of this code ?</p><pre>#include &lt;iostream&gt;<br>#include &lt;cstring&gt;<br><br>// please note -&gt;void return<br>void func(int a, int b){<br>    int c = a + b;<br>    std::cout &lt;&lt; &quot;The sum is: &quot; &lt;&lt; c &lt;&lt; std::endl;<br>}<br><br>// please note -&gt;int return<br>int func(int a, int b){<br>    int c = a + b;<br>    std::cout &lt;&lt; &quot;The sum is: &quot; &lt;&lt; c &lt;&lt; std::endl;<br>    return c;<br>}<br><br>int main(){<br>    func(2,3);<br>    return 0;<br>}</pre><p>This generate a compile time error, because func(int,int) has two definitions. Here we need to note <strong>return type is <em>not</em> considered part of a function’s signature</strong> for <em>overloading</em> purposes. However, it is possible to overload function templates based on return type alone.</p><p>Guess the output of this example below:</p><pre>#include &lt;iostream&gt;<br>#include &lt;cstring&gt;<br><br>template &lt;typename T1, typename T2&gt;<br>auto Greater(T1 a, T2 b) {<br>    std::cout&lt;&lt;__PRETTY_FUNCTION__&lt;&lt;std::endl;<br>    return a &gt; b ? a : b;<br>}<br><br>template &lt;typename TResult, typename T1, typename T2&gt;<br>TResult Greater(T1 a, T2 b) {<br>    std::cout&lt;&lt;__PRETTY_FUNCTION__&lt;&lt;std::endl;<br>    return a &gt; b ? a : b;<br>}<br><br>int main(){<br>    auto r1 = Greater(1, 2.5f);<br>    auto r2 = Greater&lt;float&gt;(7, 7.5f);<br>    return 0;<br>}</pre><p>Note that signature of function templates also includes typenames. In the example above there are two overloads one with two typenames and another with three typenames. As Greater(1, 2.5f) provides info about two types (int, float) , first function template will be instantiated.</p><p>However, Greater&lt;float&gt;(7, 7.5f) is more involved case. If compiler tries to use first overload, it would <strong><em>need to convert</em></strong> first argument 7 into float as we are only providing one template argument in &lt;float&gt; while type of second argument it would deduce as float from 7.5f. But if it tries to use second overload, it would deduce TResult as float from &lt;float&gt; , T1,T2 would be deduced ad int,float from function argument7, 7.5f. In function overloading, conversion is ranked lower than no-conversion. As we can see the compiler need not perform any type conversion in second case, it would use second overload. This is the output:</p><p>auto Greater(T1, T2) [with T1 = int; T2 = float]<br>TResult Greater(T1, T2) [with TResult = float; T1 = int; T2 = float]</p><p>If we did not have second overload, compiler will use first one. The type of T1 will be taken as float from &lt;float&gt; ,7 will be converted to float while type of T2 will be taken as float from second argument 7.5f.</p><p>Q.<strong>Which template function will be used by this line ?</strong></p><p>auto r2 = Greater&lt;int&gt;(7, 7.5f);</p><p><strong>A</strong>. If compiler tries to use first overload T1 will beint from &lt;int&gt; and T2 will be deduced as float from 7.5f. So T1, T2 → int, float</p><p>If compiler tries to use second overload TResult will be int from &lt;int&gt;, T1,T2 will be deduced from function arguments as int,float. So T1, T2 → int, float</p><p>As both overloads are deducing T1, T2 → int, float and no type conversion is getting performed in both overloads. Both of these function templates are exact match in this case. This is an ambiguity and compiler will generate an error.</p><pre>error: call of overloaded ‘Greater&lt;int&gt;(int, float)’ is ambiguous<br>   18 |     auto r2 = Greater&lt;int&gt;(7, 7.5f);<br>      |               ~~~~~~~~~~~~^~~~~~~~~</pre><p><strong>Q</strong>. Write which overload will be used in these cases in above example?</p><pre>auto r3 = Greater&lt;double&gt;(7, 7.5f);<br>auto r4 = Greater&lt;long&gt;(7, 7.5f);<br>auto r5 = Greater&lt;float&gt;(7.5f, 7);</pre><p><strong>A</strong>.</p><pre>auto r3 = Greater&lt;double&gt;(7, 7.5f);   // --&gt; second overload<br>auto r4 = Greater&lt;long&gt;(7, 7.5f);     // --&gt; second overload<br>auto r5 = Greater&lt;float&gt;(7.5f, 7);    // --&gt; compiler err, ambiguous function</pre><p>Reference: <a href="https://www.udemy.com/course/modcpptemplates">https://www.udemy.com/course/modcpptemplates</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a1d8354edcfd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Multithreading in C++. Part-5]]></title>
            <link>https://hksoni.medium.com/multithreading-in-c-part-5-70065a30e5e7?source=rss-9be79c07dba------2</link>
            <guid isPermaLink="false">https://medium.com/p/70065a30e5e7</guid>
            <dc:creator><![CDATA[Harish Kant Soni]]></dc:creator>
            <pubDate>Sun, 20 Apr 2025 05:39:30 GMT</pubDate>
            <atom:updated>2025-04-20T05:39:30.874Z</atom:updated>
            <content:encoded><![CDATA[<h3>Thread Coordination:</h3><p>Thread coordination includes ways in which different threads decides the order to make progress.</p><p>Below we have a program. It has three threads:</p><ul><li>First thread fetches data from network.</li><li>Second reads this data and updates the progress bar.</li><li>Third reads data only after complete data is downloaded.</li></ul><p>Below is an example of thread synchronization. In this example, reader thread waits until writer thread writes data.</p><pre>#include &lt;mutex&gt;<br>#include &lt;thread&gt;<br>#include &lt;iostream&gt;<br>#include &lt;string&gt;<br>#include &lt;chrono&gt;<br><br>using namespace std::chrono_literals;<br><br>std::mutex m;<br>bool data_written = false;<br>std::string data;<br><br>void reader(){<br> std::unique_lock&lt;std::mutex&gt; u_lock(m);<br> while (!data_written) {<br>  u_lock.unlock();<br>  std::this_thread::sleep_for(1s);<br>  u_lock.lock();<br> }<br> std::cout &lt;&lt; &quot;Data: &quot; &lt;&lt; data &lt;&lt; std::endl;<br>}<br><br>void writer(){<br> std::lock_guard&lt;std::mutex&gt; lock(m);<br> data = &quot;Hello, World!&quot;;<br> data_written = true;<br> std::cout &lt;&lt; &quot;Data written&quot; &lt;&lt; std::endl;<br>}<br><br><br>int main() {<br> std::thread t1(reader);<br> std::thread t2(writer);<br><br> t1.join();<br> t2.join();<br><br> return 0;<br>}</pre><p>In above example, we used bool data_written with while-loop to synchronize threads. We can rewrite same program using std::condition_variable as below:</p><pre>std::mutex m;<br>std::condition_variable cv;<br>std::string data;<br><br>void reader(){<br> std::unique_lock&lt;std::mutex&gt; lock(m);<br> cv.wait(lock);<br> std::cout &lt;&lt; &quot;Data read: &quot; &lt;&lt; data &lt;&lt; std::endl;<br>}<br><br>void writer(){<br> std::lock_guard&lt;std::mutex&gt; lock(m);<br> data = &quot;Hello, World!&quot;;<br> cv.notify_one();<br> std::cout &lt;&lt; &quot;Data written&quot; &lt;&lt; std::endl;<br>}</pre><p><strong>std::condition_variable</strong>:</p><ul><li>Defined in &lt;condition_variable&gt;</li><li><strong>wait()</strong> : Takes an argument of type std::unique_lock. It unlocks its argument and blocks the thread until a notification is received.</li><li><strong>wait_for() and wait_until()</strong>: Re-lock their argument if a notification is not received in time.</li><li><strong>notify_one()</strong>: Wake up one of the waiting threads.</li><li><strong>notify_all()</strong>: Wake up all waiting threads.</li></ul><p>Below is an example which has two threads. One thread prints odd numbers and another print even numbers. We use std::condition_variable to synchronize these threads to print numbers in order.</p><pre>#include &lt;mutex&gt;<br>#include &lt;thread&gt;<br>#include &lt;iostream&gt;<br>#include &lt;string&gt;<br>#include &lt;chrono&gt;<br>#include &lt;condition_variable&gt;<br><br>using namespace std::chrono_literals;<br><br>std::mutex m;<br>std::condition_variable cv_o, cv_e;<br><br>void odd_printer(){<br> for(int i = 1; i &lt; 10; i+=2){<br>  std::unique_lock&lt;std::mutex&gt; lock(m);<br>  std::cout&lt;&lt; std::to_string(i)&lt;&lt;std::endl;<br>  cv_e.notify_all();<br>  if(i == 9) break; // Avoid waiting after the last odd number<br>  cv_o.wait(lock);<br> }<br>}<br><br>void even_printer(){<br> std::this_thread::sleep_for(1s); // Ensure odd_printer runs first<br> for(int i = 2; i &lt;= 10; i+=2){<br>  std::unique_lock&lt;std::mutex&gt; lock(m);<br>  std::cout&lt;&lt; std::to_string(i) &lt;&lt;std::endl;<br>  cv_o.notify_all();<br>  if(i == 10) break;<br>  cv_e.wait(lock);<br> }<br>}<br><br><br>int main() {<br> std::thread t1(odd_printer);<br> std::thread t2(even_printer);<br><br> t1.join();<br> t2.join();<br> //std::cout &lt;&lt; data &lt;&lt; std::endl;<br> return 0;<br>}</pre><h3><strong>Condition Variables with Predicate</strong></h3><p>Let’s look again at our reader writer example:</p><pre>std::mutex m;<br>std::condition_variable cv;<br>std::string data;<br><br>void reader(){<br> std::unique_lock&lt;std::mutex&gt; lock(m);<br> cv.wait(lock);<br> std::cout &lt;&lt; &quot;Data read: &quot; &lt;&lt; data &lt;&lt; std::endl;<br>}<br><br>void writer(){<br> std::lock_guard&lt;std::mutex&gt; lock(m);<br> data = &quot;Hello, World!&quot;;<br> cv.notify_one();<br> std::cout &lt;&lt; &quot;Data written&quot; &lt;&lt; std::endl;<br>}</pre><p><strong>Lost Wakeup:</strong></p><p>There is a problem in above code. If writer thread starts first, it will call cv.notify_one();,but since reader thread has not yet started, this notification will be missed. This is called <em>Lost wakeup</em>. Now, when reader thread will start, it will wait at cv.wait(lock);, but no notification will be received. So data cannot be read.</p><p><strong>Spurious Wakeup:</strong></p><p>If reader thread has run first, it will wait at cv.wait(lock);. Even though writer has not notified, occasionally, the reader will be “spuriously” woke up. This is due to the way std::condition_variable is implemented. This is called Spurious wakeup.</p><p>To solve Lost wakeup and Spurious wakeup, we use wait() with predicate. The predicate is a function/lambda expression which returns true if notification received else false.</p><pre>std::mutex m;<br>std::condition_variable cv;<br>std::string data;<br>bool notified = false;<br><br>void reader(){<br> std::unique_lock&lt;std::mutex&gt; lock(m);<br> cv.wait(lock, []{ return notified; });<br> std::cout &lt;&lt; &quot;Data read: &quot; &lt;&lt; data &lt;&lt; std::endl;<br>}<br><br>void writer(){<br> std::lock_guard&lt;std::mutex&gt; lock(m);<br> data = &quot;Hello, World!&quot;;<br> notified = true;<br> cv.notify_one();<br> std::cout &lt;&lt; &quot;Data written&quot; &lt;&lt; std::endl;<br>}<br><br>int main() {<br> std::thread t1(writer);<br> std::this_thread::sleep_for(std::chrono::seconds(1));<br> std::thread t2(reader);<br><br> t1.join();<br> t2.join();<br><br> return 0;</pre><p>In above example, writer thread runs before reader thread. This can cause Lost wakeup case. To avoid it, we are using bool notified variable. This is used inside predicate in cv.wait(lock, []{ return notified; });. If this predicate return true, reader thread will proceed else not. We set value of notified = true; in writer thread after writing the data.</p><h3>Future and Promise</h3><p>C++ thread class does not provide a direct way to transfer data from one thread to another. The task functions passed to thread class constructor like thread(task_function), can return value but they are ignored.</p><p>So far we have been using shared variables to transfer data between threads. std::future and std::promise classes help us to transfer data between threads. We use std::future and std::promise classes together and between them they will setup a shared state between two threads which is like a one way communication channel.</p><p>A promise object is associated with a future object. Together they create a “shared state”. The promise object stores a result in the shared state. The future object gets the result from the shared state.</p><p><strong>std::future </strong>:</p><ul><li>Represents a result that is not yet available.</li><li>One of the most important classes in C++ concurrency. Works with many different asynchronous objects and operations.</li><li>An std::future object is not usually created directly. It can be obtained from and std::promise object or returned by an asynchronous operation.</li><li>Template class defined in &lt;future&gt;. The parameter is the type of the data that will be returned.</li><li>get() member function which obtains the result when ready, blocks until the operation is complete, fetches the result and returns it.</li><li>wait() blocks until the operation is complete, but do not return a result while wait_for() and wait_until() block with a timeout.</li></ul><p><strong>std::promise :</strong></p><ul><li>Template class defined in &lt;future&gt;. The parameter is the type of the result.</li><li>Constructor creates and associated std::future object and sets up the shared state with it.</li><li>get_future() member function return the associated future.</li><li>set_value() sets the result to its argument.</li><li>set_exception() indicates that an exception has occurred. This can be stored in the shared state.</li></ul><p>Below is an example of use of std::promise and std::future, in producer consumer problem.</p><pre>#include &lt;iostream&gt;<br>#include &lt;future&gt;<br>#include &lt;thread&gt;<br>#include &lt;chrono&gt;<br><br><br>void produce(std::promise&lt;int&gt;&amp; px){<br>    using namespace std::chrono_literals;<br><br>    int x = 42;<br>    std::this_thread::sleep_for(1s);<br>    std::cout &lt;&lt; &quot;Value produced: &quot; &lt;&lt; x &lt;&lt; std::endl;<br>    px.set_value(x);<br>}<br><br>void consume(std::future&lt;int&gt;&amp; fx){<br>    using namespace std::chrono_literals;<br><br>    std::this_thread::sleep_for(2s);<br>    int x = fx.get();<br>    std::cout &lt;&lt; &quot;Value received: &quot; &lt;&lt; x &lt;&lt; std::endl;<br>}<br>int main() {<br>    std::promise&lt;int&gt; prom;<br>    std::future&lt;int&gt; fut = prom.get_future();<br><br>    std::thread producer(produce, std::ref(prom));<br>    std::thread consumer(consume, std::ref(fut));<br><br>    producer.join();<br>    consumer.join();<br><br>    return 0;<br>}</pre><p>In case producer throws an error we can pass that error to the consumer, this way :</p><pre>void produce(std::promise&lt;int&gt;&amp; px){<br>    using namespace std::chrono_literals;<br>    try{<br>        int x = 42;<br>        std::this_thread::sleep_for(1s);<br>        throw std::out_of_range(&quot;Oops&quot;);<br>    }<br>    catch (...){<br>        px.set_exception(std::current_exception());<br>    }<br>}<br><br>void consume(std::future&lt;int&gt;&amp; fx){<br>    using namespace std::chrono_literals;<br><br>    std::this_thread::sleep_for(2s);<br>    try{<br>        int x = fx.get();<br>        std::cout &lt;&lt; &quot;Value received: &quot; &lt;&lt; x &lt;&lt; std::endl;<br>    }<br>    catch (std::exception&amp; e){<br>        std::cout &lt;&lt; &quot;Exception caught: &quot; &lt;&lt; e.what() &lt;&lt; std::endl;<br>    }<br>}</pre><p>You can also rewrite above produce function using std::make_exception_ptr rather than try-catch:</p><pre>void produce(std::promise&lt;int&gt;&amp; px){<br>    using namespace std::chrono_literals;<br>    px.set_exception(std::make_exception_ptr(std::out_of_range(&quot;Oops&quot;)));<br>    return;<br>}</pre><p><strong>Single Producer with multiple Consumers:</strong></p><p>std::future is designed for use with a single consumer thread. It assumes it has exclusive read access to the shared state. It cannot be shared between threads. It is move-only class.</p><p>For such cases, we use std::shared_future class:</p><ul><li>It can be copied.</li><li>Each thread has its own object.</li><li>They all share the same state with the std::promise</li><li>Calling get() or wait() from different copies is safe.</li></ul><p>Obtaining std::shared_future object :</p><ul><li>Normally we do not create a shared future directly.</li><li>We can move from an existing std::future std::shared_future&lt;int&gt; shared_fut1 = std::move(fut);</li><li>We can call share() on the std::future std::shared_future&lt;int&gt; shared_fut2 = fut.share();</li><li>We can also obtain a shared_future directly from a promise. shared_future&lt;int&gt; shared_fut = prom.get_future();</li></ul><p>In the example below, we are using one producer and two consumer threads:</p><pre>void produce(std::promise&lt;int&gt;&amp; px){<br>    using namespace std::chrono_literals;<br>    int x = 42;<br>    std::this_thread::sleep_for(1s);<br>    std::cout &lt;&lt; &quot;Value produced: &quot; &lt;&lt; x &lt;&lt; std::endl;<br>    px.set_value(x);<br>}<br><br>void consume(std::shared_future&lt;int&gt;&amp; fx){<br>    using namespace std::chrono_literals;<br><br>    std::this_thread::sleep_for(1s);<br>    int x = fx.get();<br>    std::cout &lt;&lt;&quot;thread id =&quot;&lt;&lt;std::this_thread::get_id()&lt;&lt; &quot;,Value received: &quot; &lt;&lt; x &lt;&lt; std::endl;<br>}<br>int main() {<br>    std::promise&lt;int&gt; prom;<br>    std::shared_future&lt;int&gt; sfut1 = prom.get_future();<br>    std::shared_future&lt;int&gt; sfut2 = sfut1;<br><br>    std::thread producer(produce, std::ref(prom));<br>    std::thread consumer(consume, std::ref(sfut1));<br>    std::thread consumer2(consume, std::ref(sfut2));<br><br>    producer.join();<br>    consumer.join();<br>    consumer2.join();<br><br>    return 0;<br>}</pre><h3>Atomic Types</h3><ul><li>When we make a variable atomic type, all the operation on this variable will also be atomic.</li><li>In C++, we use &lt;atomic&gt; header for these variables. The parameter is the type of object.</li><li>The object must be initialized. atomic&lt;int&gt; x = 0;</li><li>This parameter must be a type which is “trivially copyable” which means built-in type or classes which has all member built-in types.</li><li>We can assign to and from the object. <br>x = 2; // Atomic assignment to x<br>y = x; // Atomic assignment from x, y can be non-atomic</li></ul><p>In the example given below, we are creating 10 threads. Each thread is running ++ operator on variable x, 1000 times.</p><pre>int x = 0;<br><br>void task_func(){<br>    for (int i = 0; i &lt; 1000; ++i) {<br>        x++;<br>    }<br>}<br><br>int main(){<br>    std::vector&lt;std::thread&gt; threads;<br>    for (int i = 0; i &lt; 10; ++i) {<br>        threads.push_back(std::thread(task_func));<br>    }<br>    for (auto&amp; t : threads) {<br>        t.join();<br>    }<br>    std::cout &lt;&lt; &quot;Final value of x: &quot; &lt;&lt; x &lt;&lt; std::endl;<br>    // Check if x is equal to 10000<br>    return 0;<br>}<br>//output:<br>// Final value of x: 9632</pre><p>After execution of the code above, value of x is less that 10000 because ++x operation is not atomic. Let’s make x atomic and try again.</p><p>Modify above code and declare x an atomic variable :</p><p>std::atomic&lt;int&gt; x = 0;</p><p>After this above code works fine and x becomes 10000 after the code runs.</p><p><strong>Atomic Operations:</strong></p><p>The atomic template defines some member functions.</p><ul><li>store() : Atomically replace the object’s value with its argument.</li><li>load() : Atomically return the object’s value</li><li>operator =()</li><li>operator T() : Synonyms for store() and load()</li><li>exchange() : Atomically replace the object’s value with its argument, returns the previous value.</li></ul><p>Atomic pointers support pointer arithmetic:</p><ul><li>increment and decrement operators</li><li>fetch_add() synonym for x++</li><li>fetch_sub() synonym for x —</li><li>+= and -= operators</li></ul><p>Interger Specializations have these above and atomic bitwise logical operations &amp;, |, ^</p><pre>#include &lt;iostream&gt;<br>#include &lt;atomic&gt;<br><br>int main(){<br>    std::atomic&lt;int&gt; x = 0;<br>    x = 2;<br>    int y = x;<br>    x.store(3);<br>    std::cout &lt;&lt;&quot;After store: &quot; &lt;&lt; x.load() &lt;&lt; std::endl;<br>    std::cout &lt;&lt;&quot;Exchange returns = &quot; &lt;&lt; x.exchange(y) &lt;&lt; std::endl;<br>    std::cout &lt;&lt;&quot;After exchange: &quot; &lt;&lt; x.load() &lt;&lt; std::endl;<br>    return 0;<br>}<br>// ************output*********<br>// After store: 3<br>// Exchange returns = 3<br>// After exchange: 2</pre><p><strong>std::atomic_flag</strong></p><p>This is bool specialization of atomic template. This atomic flag is simple class and it has less overhead. There are only 3 things that can be done with it:</p><ul><li>clear() : sets flag to false.</li><li>test_and_set() : sets flag to true and returns previous value.</li><li>operator = ()</li></ul><p>It must be initialized to false:</p><p>atomic_flag lock = ATOMIC_FLAG_INIT;</p><p><strong>Spin Lock:</strong></p><p>A spin lock is essentially an infinite loop, it keeps spinning until a condition becomes true. It’s an alternative to locking a mutex or using a condition variable. We can use std::atomic_flag to implement a basic spin lock. The loop condition is the value of the flag.</p><ul><li>Each thread calls test_and_set() in a loop.</li><li>If this returns true:<br>- Some other thread has set the flag and is in the critical section.<br>- Iterate again</li><li>If it returns false:<br>- This thread has set the flag<br>- Exit the loop and proceed into the critical section</li><li>After the critical section, set the flag to false<br>- This allows another thread to execute in the critical section</li></ul><pre>#include &lt;iostream&gt;<br>#include &lt;atomic&gt;<br>#include &lt;thread&gt;<br>#include &lt;vector&gt;<br>#include &lt;chrono&gt;<br><br>using namespace std::chrono_literals;<br><br>std::atomic_flag flag = ATOMIC_FLAG_INIT;<br><br>void task(int n){<br>    //loop until we can set the flag<br>    while(flag.test_and_set()){}<br>    // critical section<br>    std::this_thread::sleep_for(1s);<br>    std::cout &lt;&lt; &quot;Task &quot; &lt;&lt; n &lt;&lt; &quot; is running\n&quot;;<br>    // clear the flag<br>    flag.clear();<br>}<br><br>int main() {<br>    std::vector&lt;std::thread&gt; threads;<br>    for (int i = 0; i &lt; 10; ++i) {<br>        threads.emplace_back(task, i);<br>    }<br>    for (auto&amp; t : threads) {<br>        t.join();<br>    }<br>    return 0;<br>}<br>// ************output*********<br>Task 1 is running<br>Task 9 is running<br>Task 6 is running<br>Task 7 is running<br>Task 8 is running<br>Task 5 is running<br>Task 3 is running<br>Task 4 is running<br>Task 2 is running<br>Task 0 is running</pre><p>Above code can also be rewritten using mutex like this</p><pre>using namespace std::chrono_literals;<br>std::mutex mtx; // mutex for critical section<br>void task(int n){<br>    std::lock_guard&lt;std::mutex&gt; lock(mtx); // lock the mutex<br>    // critical section<br>    std::this_thread::sleep_for(1s);<br>    std::cout &lt;&lt; &quot;Task &quot; &lt;&lt; n &lt;&lt; &quot; is running\n&quot;;<br>    <br>}</pre><p><strong>Pro and cons of spin lock:</strong></p><ul><li>A spinning thread remains active while a mutex may block the thread. It is possible that the scheduler may take that thread iff the core, and let a different thread run.</li><li>When the spinning thread gets the lock, it can continue immediately. There is nothing it needs to do to start again. With a mutex, the thread may need to be woken up. If it has been taken off the core, it may need to be reloaded.</li><li>Spin lock if processor intensive. You have a core which is running flat out, not doing any useful work. We want this thread to be spinning for the shortest time possible.</li></ul><h3>Asynchronous Programming:</h3><p><strong>std::packaged_task:</strong></p><ul><li>Defined in &lt;future&gt;</li><li>Encapsulates a task<br>- A callable object for the task’s code<br>- An std::promise for the result of the task</li><li>Provides a higher level of abstraction</li><li>Template class<br>- The parameter is the callable object’s signature<br>- example <em>std::packaged_task&lt;int(int, int)&gt; ptask(…);</em></li><li>The constructor takes the callable object as argument</li><li>Functor class</li><li>Overloaded operator()<br>- Invokes the callable object<br>- Stores the return value in the promise object</li><li>get_future()<br>- Return the std::future object associated with the promise</li><li>std::packaged_task is a move-only class</li></ul><p><strong>Using an std::packaged_task Object</strong>:</p><ul><li>Pass a callable object to the constructor</li><li>The packaged task starts when operator() is called<br>- In the same thread, by calling it directly<br>- In a new thread, by passing the task to std::thread’s constructor</li><li>We call get_future()</li><li>We call get() on the returned future object<br>- Or wait() and friends</li></ul><pre>#include &lt;iostream&gt;<br>#include &lt;future&gt;<br>#include &lt;chrono&gt;<br>#include &lt;thread&gt;<br><br>using namespace std::literals;<br><br>int main(){<br>    std::packaged_task&lt;int(int,int)&gt; task([](int a, int b) {<br>        std::this_thread::sleep_for(2s);<br>        return a + b;<br>    });<br><br>    std::future&lt;int&gt; fut = task.get_future();<br>    task(1, 2);<br><br>    std::cout &lt;&lt; &quot;Waiting for the result...\n&quot;;<br>    std::cout &lt;&lt; &quot;Result: &quot; &lt;&lt; fut.get() &lt;&lt; &quot;\n&quot;;<br><br>    return 0;<br>}<br>// ********** output ****************<br>// Waiting for the result...<br>// Result: 3</pre><p>When we execute above code it waits for 2 sec and then suddenly output is shown as</p><pre>Waiting for the result...<br>Result: 3</pre><p>This happens because task(1, 2); will wait for 2 sec. This task is running in the main thread. If we want to run this task in a separate thread :</p><pre>#include &lt;iostream&gt;<br>#include &lt;future&gt;<br>#include &lt;chrono&gt;<br>#include &lt;thread&gt;<br><br>using namespace std::literals;<br><br>int main(){<br>    std::packaged_task&lt;int(int,int)&gt; task([](int a, int b) {<br>        std::this_thread::sleep_for(2s);<br>        return a + b;<br>    });<br><br>    std::future&lt;int&gt; fut = task.get_future();<br>    std::thread t(std::move(task), 1, 2);<br><br>    std::cout &lt;&lt; &quot;Waiting for the result...\n&quot;;<br>    std::cout &lt;&lt; &quot;Result: &quot; &lt;&lt; fut.get() &lt;&lt; &quot;\n&quot;;<br>    t.join();<br><br>    return 0;<br>}</pre><p>This code also prints out as above code, but first Waiting for the result… is printed and after 2 sec Result: 3 is printed.</p><h3>std::async()</h3><ul><li>Defined in &lt;future&gt;</li><li>Higher level abstraction than std::thread<br>- We can execute a task with std::async() which runs in the background<br>- This allows us to do other work while the task is running<br>- Alternatively, it can run synchronously in the same thread.</li><li>Similar syntac to std::thread’s constructor<br>- The task function is the first argument<br>- Followed by the arguments to the function</li></ul><pre>void hello() {<br>    std::cout &lt;&lt; &quot;Hello, Async!&quot; &lt;&lt; std::endl;<br>}<br><br>int main(){<br>    std::async(hello);<br>    return 0;<br>}</pre><p>This is the simplest code demonstrating use of std::async.</p><p>Above code gives a warning about ignoring return value.</p><ul><li>std::async() returns an std::future object<br>- This contains the result of the task.</li><li>We can call get() on the future<br>- Or wait() and friends</li><li>This can be done in a different thread from the call to std::async()</li></ul><pre>unsigned long fib(unsigned long n) {<br>    if (n &lt;= 1) return n;<br>    return fib(n - 1) + fib(n - 2);<br>}<br><br>int main(){<br>    std::cout &lt;&lt; &quot;Calling fib(25) \n&quot;;<br><br>    auto result =  std::async(fib, 45);<br><br>    using namespace std::literals;<br>    while(result.wait_for(1s) != std::future_status::ready){<br>        std::cout &lt;&lt;&quot;Waiting for result...\n&quot;;<br>    }<br>    std::cout &lt;&lt; result.get() &lt;&lt; &quot;\n&quot;;<br>    return 0;<br>}</pre><p>output:</p><pre>Calling fib(25) <br>Waiting for result...<br>Waiting for result...<br>Waiting for result...<br>Waiting for result...<br>Waiting for result...<br>1134903170</pre><h3>std::async and Exceptions</h3><ul><li>The task may throw an exception</li><li>The exception is stored in the future object</li><li>It will be re-thrown when get() is called<br>- Similar to using an explicit std::promise</li></ul><pre>int produce(){<br>    int x = 45;<br><br>    using namespace std::literals;<br>    std::this_thread::sleep_for(1s);<br><br>    if(1){<br>        throw std::out_of_range(&quot;Error: out of range&quot;);<br>    }<br>    std::cout &lt;&lt; &quot;Produce returning : &quot; &lt;&lt; x &lt;&lt; &quot;\n&quot;;<br>    return x;<br>}<br><br>int main(){<br>    auto result = std::async(produce);<br><br>    std::cout &lt;&lt; &quot;Future calling get()...\n&quot;;<br>    try{<br>        auto x = result.get();<br>        std::cout &lt;&lt; &quot;Future returned: &quot; &lt;&lt; x &lt;&lt; &quot;\n&quot;;<br>    }<br>    catch(std::exception&amp; e){<br>        std::cout &lt;&lt; &quot;Exception caught: &quot; &lt;&lt; e.what() &lt;&lt; &quot;\n&quot;;<br>    }<br>    return 0;<br>}</pre><p><strong>std::async() and Launch Options:</strong></p><ul><li>std::async() may start a new thread for the task</li><li>Or it may run the task in the same thread</li><li>Controlled by the “launch flag”<br>- Optional argument to std::async()</li><li>std::launch:async<br>- A new thread is started for the task<br>- The task is executed as soon as the thread starts</li><li>std::launch::deferred<br>- Nothing happens until get() is called on the returned future<br>- The task is then executed (“Lazy evaluation”)</li><li>If both flags are set<br>- The implementation decides whether to start a new thread<br>- This is default</li></ul><p>Default Launch Policy:</p><ul><li>Lack of certainty<br>- The task could execute synchronously with the initiating thread<br>- The task could execute concurrently with the initiating thread<br>- It could execute concurrently with the thread that calls get()<br>- If get() is not called, the task may not execute at all</li><li>Thread -local storage<br>- We do not know which thread’s data will be used</li></ul><pre>#include &lt;iostream&gt;<br>#include &lt;future&gt;<br>#include &lt;chrono&gt;<br>#include &lt;thread&gt;<br>#include &lt;string&gt;<br><br>using namespace std::literals::string_literals;<br><br>int task(){<br>    std::cout&lt;&lt;&quot;Running task in thread id:&quot;&lt;&lt;std::this_thread::get_id() &lt;&lt;std::endl;<br>    std::this_thread::sleep_for(std::chrono::seconds(2));<br>    return 42;<br>}<br><br>void func(std::string option=&quot;default&quot;s){<br>    std::future&lt;int&gt; result;<br>    if(option == &quot;async&quot;){<br>        result = std::async(std::launch::async, task);<br>    } else if(option == &quot;deferred&quot;){<br>        result = std::async(std::launch::deferred, task);<br>    } else {<br>        result = std::async(task);<br>    }<br><br>    std::cout &lt;&lt; &quot;Calling async with option: &quot; &lt;&lt; option &lt;&lt; std::endl;<br>    std::this_thread::sleep_for(std::chrono::seconds(1));<br>    std::cout &lt;&lt;&quot;get() result: &quot; &lt;&lt; result.get() &lt;&lt; std::endl;<br>}<br><br>int main(){<br>    std::cout &lt;&lt;&quot;Running main in thread id:&quot; &lt;&lt; std::this_thread::get_id() &lt;&lt; std::endl;<br>    func(&quot;async&quot;);<br>    func(&quot;deferred&quot;);<br>    func(&quot;default&quot;);<br>    return 0;<br>}</pre><p>output:</p><pre>Running main in thread id:140589609158464<br>Calling async with option: async<br>Running task in thread id:140589609154240<br>get() result: 42<br>Calling async with option: deferred<br>get() result: Running task in thread id:140589609158464<br>42<br>Calling async with option: default<br>Running task in thread id:140589609154240<br>get() result: 42</pre><p>In this output, we can see that with std::launch::async , task() started in new thread immediately in new thread that’s why we see Running task in thread id:140589609154240 before get() result: 42. However, with std::launch::deferred task() does not start until get() is called. That’s why we see get() result: before Running task in thread id:140589609158464</p><p><strong>Launch Policy Recommendations:</strong></p><p>Use the async launch option if any of these are ture</p><ul><li>The task must execute in a separate thread</li><li>The task must start immediately</li><li>The task will use thread-local storage</li><li>The task function must be executed, even if get() is not called</li><li>The thread receiving the future will call wait_for() or wait_until()</li></ul><p>Use the deferred launch option if</p><ul><li>The task must be run in the thread which calls get()</li><li>The task must be executed, even if no more threads can be created</li><li>You want lazy execution of the task</li></ul><p>Otherwise, let the implementation choose.</p><p><strong>Return Value from wait() and Friends:</strong></p><ul><li>wait()<br>- Returns nothing</li><li>wait_for() and wait_until()<br>- Return std::future_status::ready if the result is available.<br>- Return std::future_status::timeout is the timeout has expired.<br>- Return std::future_status::deferred if the result is being lazily evaluated.</li><li>In lazy evaluation, the task does not run until get() is called.</li></ul><p><strong>Choosing a Thread Object:</strong></p><p>We now have 3 different ways to execute a task:</p><ul><li>Create an std::thread object</li><li>Create an std::packaged_task object</li><li>Call std::async</li></ul><p><strong>Advantage os std::async()</strong></p><ul><li>The simplest way to execute a task<br>- Easy to obtain the return value from a task<br>- Or to catch any execption thrown is the task<br>- Choice of running the task synchronously or asynchronously</li><li>Higher-level abstraction than std::thread<br>- The library manages the threads for the programmer<br>- And the inner-thread communication<br>- No need to use shared data</li></ul><p><strong>Disadvantages of async()</strong></p><ul><li>Cannot detach tasks</li><li>A task executed with std::launch::async is “implicitly joined”</li><li>The returned future’s destructor will block until the task completes</li></ul><pre>void task(){<br>    std::this_thread::sleep_for(5s);<br>    std::cout &lt;&lt; &quot;Task result: &quot; &lt;&lt; 42 &lt;&lt; std::endl;<br>}<br><br>void func(){<br>    std::cout &lt;&lt; &quot;Calling async&quot; &lt;&lt; std::endl;<br>    auto result = std::async(std::launch::async, task);<br>}<br><br>int main(){<br>    func();<br>    std::cout &lt;&lt; &quot;Task started&quot; &lt;&lt; std::endl;<br>    return 0;<br>}</pre><p>output:</p><pre>Calling async<br>Task result: 42<br>Task started</pre><p>In above code when func() completes destructor of result object is called which will wait until task is not completed.</p><p><strong>Advantage of std::packaged_task:</strong></p><ul><li>The best choice of we want to represent tasks as objects<br>- e.g. to create a container of tasks</li><li>A lower-level abstraction that std::async()<br>- Can control when a task is executed<br>- Can control on which thread it is executed</li></ul><p><strong>Advantage of std::thread:</strong></p><ul><li>The most flexible<br>- Allow access of the underlying software thread<br>- Useful for features not supported by standard C++<br>- Can be detached</li></ul><p><strong>Recommendations:</strong></p><ul><li>For starting a new thread in general<br>- Use std::async()</li><li>For container of thread objects<br>- Use std::packaged_task</li><li>For starting a detachable thread or for more specialized requirements<br>- Use std::thread</li></ul><p>Reference: <a href="https://www.udemy.com/course/learn-modern-cplusplus-concurrency">https://www.udemy.com/course/learn-modern-cplusplus-concurrency</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=70065a30e5e7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Multithreading in C++. Part-4]]></title>
            <link>https://hksoni.medium.com/multithreading-in-c-part-4-e24af312e0be?source=rss-9be79c07dba------2</link>
            <guid isPermaLink="false">https://medium.com/p/e24af312e0be</guid>
            <category><![CDATA[cplusplus]]></category>
            <category><![CDATA[multithreading]]></category>
            <dc:creator><![CDATA[Harish Kant Soni]]></dc:creator>
            <pubDate>Tue, 01 Apr 2025 17:24:30 GMT</pubDate>
            <atom:updated>2025-04-01T17:24:30.256Z</atom:updated>
            <content:encoded><![CDATA[<h3>Lazy initialization:</h3><ul><li>Common pattern in functional programming.</li><li>A variable is only initialized when it is first used.</li><li>This is useful when the variable is expensive to construct.</li><li>Can be used in multithreaded code.</li></ul><pre>// Lazy initialization(Single threaded)<br>class Test{<br>    //...<br>public:<br>    void func(){ //.... }<br>};<br><br>Test* ptest = nullptr; //variable to be lazy initialized<br><br><br>void process(){<br>    if(!ptest){ <br>        ptest = new Test();<br>    }<br>    ptest-&gt;func();<br>}</pre><p>In above example, ptest is only initialized when it is needed for the first time. Above example work in single threaded environment, but not in multithreaded environment.</p><p><strong>Q. Is above example thread safe? If not, why?</strong></p><p><strong>A.</strong> Above example in not thread safe, because in process() critical section is initialization on ptest variable. This line is critical section.</p><p>ptest = new Test();</p><p>When ptest is nullptr multiple threads can pass if(!ptest) check. All these threads will now run ptest = new Test(); . This will cause memory leak and multiple initialization of ptest .</p><p><strong>Q. How can we make is thread-safe?</strong></p><p><strong>A</strong>. We can start by protecting the critical section with mutex.</p><pre>#include&lt;mutex&gt;<br>// Lazy initialization(Single threaded)<br>class Test{<br>    //...<br>public:<br>    void func(){ //.... }<br>};<br><br>Test* ptest = nullptr; //variable to be lazy initialized<br>std::mutex mtx;<br><br>void process(){<br>    std::unique_lock&lt;std::mutex&gt; ulock(mtx);<br>    if(!ptest){ <br>        ptest = new Test();<br>    }<br>    ulock.unlock();<br>    ptest-&gt;func();<br>}</pre><p>Although this is thread-safe, it’s not very efficient. We only need to lock the mutex when we initialize ptest variable, if ptest is already initialized, mutex locking is not needed. This case is similar to single write multiple reader issue.</p><p>In the above example, every thread calling process(), locks the mutex. Locking the mutex blocks other threads which call process(). This causes loss of performance.</p><p>This issue can be solved using shared_lock as given below:</p><pre>#include &lt;mutex&gt;<br>#include &lt;shared_mutex&gt;<br><br>// Lazy initialization (Thread-safe using std::shared_mutex)<br>class Test {<br>    //...<br>public:<br>    void func() { /*...*/ }<br>};<br><br>Test* ptest = nullptr; // Variable to be lazy initialized<br>std::shared_mutex sharedMtx;<br><br>void process() {<br>    {<br>        // Acquire a shared lock for reading<br>        std::shared_lock&lt;std::shared_mutex&gt; sharedLock(sharedMtx);<br>        if (ptest) {<br>            // If already initialized, use it<br>            ptest-&gt;func();<br>            return;<br>        }<br>    }<br><br>    // Acquire an exclusive lock for writing<br>    std::unique_lock&lt;std::shared_mutex&gt; uniqueLock(sharedMtx);<br>    if (!ptest) { // Check again to ensure initialization happens only once<br>        ptest = new Test();<br>    }<br>    uniqueLock.unlock();<br><br>    // Safe to use ptest after initialization<br>    ptest-&gt;func();<br>}</pre><p>When shared_mutex wasn’t available in C++, double check locking was used.</p><pre>#include &lt;mutex&gt;<br><br>// Lazy initialization (Thread-safe with double-checked locking)<br>class Test {<br>    //...<br>public:<br>    void func() { /*...*/ }<br>};<br><br>Test* ptest = nullptr; // Variable to be lazy initialized<br>std::mutex mtx;<br><br>void process() {<br>    if (!ptest) { // First check (not locked)<br>        std::unique_lock&lt;std::mutex&gt; ulock(mtx);<br>        if (!ptest) { // Second check (locked)<br>            ptest = new Test();<br>        }<br>    }<br>    ptest-&gt;func();<br>}</pre><p><strong>Q. Why do we need 2 checks ?</strong></p><p><strong>A. </strong>Initially when ptest is nullptr ,multiple threads(let’s say t1, t2, t3) can pass first check. Only one of these threads(let’s say t1) will acquire the lock on mutex. If ptest is still nullptr, only this thread(t1) will initialize ptest. Now, t2 and t3 will acquire the lock one at a time. Since ptest is already initialized by t1 thread, second check will fail. Thus ptest is only initialized once.</p><p>There is one more problem in the above code in this ptest = new Test();. This statement involve multiple steps:</p><ol><li>Allocating memory for object.</li><li>Initializing this memory.</li><li>Assigning address of this memory to ptest variable.</li></ol><p>Prior to C++17, order of these steps could be 1–2–3 or 1–3–2. It was dependent on the compiler in which order it was implemented. This could lead to undefined behavior for double check lock method in some cases.</p><p>Let’s say a compiler executes above steps in 1–3–2 order. Thread t1 has passed first check, acquired the lock and passed second check as well. Thread t1 starts executing the statement ptest = new Test(); . It allocated memory(step 1), assigned address of this memory to ptest(step 3), it has not yet initialized this memory(step 2). Another thread (let’s say t4), reached first check, it finds t1 is not nullptr so it would fail first check and execute ptest-&gt;func();. As t1 has not yet initialized this address, it would lead to undefined behavior.</p><p>However, in C++17 now the order of above steps is defined in 1–2–3 order so above problem does not occur in C++17 onwards.</p><p>Apart from using double check and std::shared_mutex, C++11 provided one more way to achieve lazy initialization using std::call_once.</p><h4>std::call_once:</h4><ul><li>A given function is only called once.</li><li>It is done in one thread.</li><li>The thread cannot be interrupted until the function call completes.</li><li>It is often used with std::once_flag.</li></ul><pre>  #include &lt;mutex&gt;<br>  #include &lt;memory&gt;<br>  <br>  // Lazy initialization (Thread-safe with single-reader, multiple-writer)<br>  class Test {<br>      //...<br>  public:<br>      void func() { /*...*/ }<br>  };<br>  <br>  Test* ptest = nullptr; // Smart pointer for automatic cleanup<br>  std::once_flag ptest_flag;<br>  <br>  void process() {<br>      // Ensure ptest is initialized only once<br>      std::call_once(ptest_flag, []() {<br>          ptest = new Test();<br>      });<br>  <br>      // Safe to use ptest after initialization<br>      ptest-&gt;func();<br>  }</pre><p>There is one more way for lazy initialization. It is called Meyer’s singleton with static local variable. It is shown below :</p><pre>#include &lt;thread&gt;<br><br>class Test {<br>    //...<br>public:<br>    void func() { /*...*/ }<br>};<br><br>void process() {<br>    static Test test;<br>    ptest-&gt;func();<br>}<br><br>int main(){<br>    std::thread t1(process);<br>    std::thread t2(process);<br>    t1.join();<br>    t2.join();<br>    return 0;<br>}</pre><p>In the above example, when first time process() is called, it will initialize test variable. Next time onwards, it will use this initialized variable again and again.</p><p>So there are 5 ways for lazy initialization in C++:</p><ol><li>Naive use of std::mutex.</li><li>Using std::shared_mutex with multiple reader single write way.</li><li>Double-checked locking with C++17 compiler or later</li><li>Using std::call_once .</li><li>Meyer’s singleton with static local variable.</li></ol><h3>Deadlock:</h3><p>Deadlocks is second most common problem after data races in multithreaded programs. Deadlock is a situation when thread A is waiting for thread B to do something and thread B is waiting for thread A to do something. In the example below, thread A acquires mutex 1 and waits for mutex 2. Similarly thread B acquires mutex 2 and waits for mutex 1 which leads to deadlock.</p><pre>#include &lt;thread&gt;<br>#include &lt;mutex&gt;<br>#include &lt;chrono&gt;<br><br>std::mutex m1,m2;<br><br>void threadA(){<br>    std::lock_guard&lt;std::mutex&gt; l1(m1);<br>    std::this_thread::sleep_for(std::chrono::milliseconds(100));<br>    std::lock_guard&lt;std::mutex&gt; l2(m2);<br>    std::this_thread::sleep_for(std::chrono::milliseconds(100));<br>}<br><br>void threadB(){<br>    std::lock_guard&lt;std::mutex&gt; l2(m2);<br>    std::this_thread::sleep_for(std::chrono::milliseconds(100));<br>    std::lock_guard&lt;std::mutex&gt; l1(m1);<br>    std::this_thread::sleep_for(std::chrono::milliseconds(100));<br>}<br><br>int main(){<br>    std::thread t1(threadA);<br>    std::thread t2(threadB);<br>    t1.join();<br>    t2.join();<br>    return 0;<br>}</pre><p>To avoid deadlock with mutexes, we need to follow these rules:</p><ul><li>All threads should lock the mutexes in the same order.</li><li>Lock multiple mutexes in a single operation: Thread A locks mutex m1, m2 together now thread B cannot lock either m1 or m2.</li></ul><h3>std::scoped_lock:</h3><ul><li>C++17 added std::scoped_lock.</li><li>Its use is similar to std::lock_guard, but it takes multiple mutexes as input.</li><li>The mutexes are locked in the order given in the constructor call. In the destructor, the mutexes are unlocked in the reverse order.</li><li>This avoids the possibility of deadlock with multiple mutexes.</li></ul><pre>#include &lt;thread&gt;<br>#include &lt;mutex&gt;<br>#include &lt;chrono&gt;<br>#include &lt;iostream&gt;<br><br>std::mutex m1,m2;<br><br>void threadA(){<br>    std::cout &lt;&lt; &quot;Thread A: Trying to lock m1 and m2&quot; &lt;&lt; std::endl;<br>    std::scoped_lock s_lock(m1,m2);<br>    std::cout &lt;&lt; &quot;Thread A: Acquired locks m1 and m2&quot; &lt;&lt; std::endl;<br>    std::this_thread::sleep_for(std::chrono::milliseconds(100));<br>    std::cout &lt;&lt; &quot;Thread A: Releasing locks m1 and m2&quot; &lt;&lt; std::endl;<br>}<br><br>void threadB(){<br>    std::cout &lt;&lt; &quot;Thread B: Trying to lock m2 and m1&quot; &lt;&lt; std::endl;<br>    std::scoped_lock s_lock(m2,m1);<br>    std::cout &lt;&lt; &quot;Thread B: Acquired locks m2 and m1&quot; &lt;&lt; std::endl;<br>    std::this_thread::sleep_for(std::chrono::milliseconds(100));<br>    std::cout &lt;&lt; &quot;Thread B: Releasing locks m2 and m1&quot; &lt;&lt; std::endl;<br>}<br><br>int main(){<br>    std::thread t1(threadA);<br>    std::thread t2(threadB);<br>    t1.join();<br>    t2.join();<br>    return 0;<br>}<br>// ********output*********<br>// Thread B: Trying to lock m2 and m1<br>// Thread B: Acquired locks m2 and m1<br>// Thread A: Trying to lock m1 and m2<br>// Thread B: Releasing locks m2 and m1<br>// Thread A: Acquired locks m1 and m2<br>// Thread A: Releasing locks m1 and m2</pre><p>In above example std::scoped_lock s_lock(m2,m1);, locks m2 and m1 together which avoids deadlock.</p><h3>std::lock:</h3><p>If you are not using C++17 or higher, you can use std::lock to lock multiple mutexes together, but you need to unlock them manually. Here is the syntax.</p><p>std::lock(m1,m2);</p><p>You can either unlock these mutexes using m1.unlock() or use std::unique_lock with std::adopt_lock to unlock these mutexes automatically. Here is an example:</p><pre>#include &lt;thread&gt;<br>#include &lt;mutex&gt;<br>#include &lt;chrono&gt;<br>#include &lt;iostream&gt;<br><br>using namespace std::literals;<br><br>std::mutex m1,m2;<br><br>void threadA(){<br>    std::cout&lt;&lt;&quot;Thread A: Trying to lock m1 and m2\n&quot;;<br>    std::lock(m1,m2); // Locks m1 and m2<br>    std::cout&lt;&lt;&quot;Thread A: Acquired locks m1 and m2\n&quot;;<br><br>    // adopt the locks<br>    std::unique_lock&lt;std::mutex&gt; lk1(m1,std::adopt_lock);<br>    std::unique_lock&lt;std::mutex&gt; lk2(m2,std::adopt_lock);<br>    std::cout&lt;&lt;&quot;Thread A has adopted locks m1 and m2\n&quot;;<br><br>    std::this_thread::sleep_for(1s);<br>    std::cout&lt;&lt;&quot;Thread A: Releasing locks m1 and m2\n&quot;;<br>}<br><br>void threadB(){<br>    std::cout&lt;&lt;&quot;Thread B: Trying to lock m2 and m1\n&quot;;<br>    std::lock(m2,m1); // Locks m2 and m1<br>    std::cout&lt;&lt;&quot;Thread B: Acquired locks m2 and m1\n&quot;;<br><br>    // adopt the locks<br>    std::unique_lock&lt;std::mutex&gt; lk1(m2,std::adopt_lock);<br>    std::unique_lock&lt;std::mutex&gt; lk2(m1,std::adopt_lock);<br>    std::cout&lt;&lt;&quot;Thread B has adopted locks m2 and m1\n&quot;;<br>    std::this_thread::sleep_for(1s);<br>    std::cout&lt;&lt;&quot;Thread B: Releasing locks m2 and m1\n&quot;;<br>}<br><br>int main(){<br>    std::thread t1(threadA);<br>    std::thread t2(threadB);<br>    t1.join();<br>    t2.join();<br>    return 0;<br>}</pre><p>We can also use std::defer_lock with std::unique_lock to achieve same results as above. Here is an example:</p><pre>#include &lt;thread&gt;<br>#include &lt;mutex&gt;<br>#include &lt;chrono&gt;<br>#include &lt;iostream&gt;<br><br>using namespace std::literals;<br><br>std::mutex m1,m2;<br><br>void threadA(){<br>    std::unique_lock&lt;std::mutex&gt; lk1(m1,std::defer_lock);<br>    std::unique_lock&lt;std::mutex&gt; lk2(m2,std::defer_lock);<br>    std::lock(m1,m2); // Locks m1 and m2<br>}<br><br>void threadB(){<br>    std::unique_lock&lt;std::mutex&gt; lk1(m2,std::defer_lock);<br>    std::unique_lock&lt;std::mutex&gt; lk2(m1,std::defer_lock);<br>    std::lock(m2,m1); // Locks m2 and m1<br>}<br><br>int main(){<br>    std::thread t1(threadA);<br>    std::thread t2(threadB);<br>    t1.join();<br>    t2.join();<br>    return 0;<br>}</pre><h3>std::try_lock:</h3><p>std::try_lock tries to lock multiple mutextes without blocking. It returns:</p><ul><li>Returns -1 is it was able to lock all mutexes.</li><li>Returns index of the mutex which could not be locked.</li></ul><p>Example syntax:</p><p>std::try_lock(m1,m2,m3)</p><h3>Deadlock practical:</h3><p>We are going to solve classic Dining Philosophers problem. There are 5 philosophers sitting around a table with 5 forks as show in the image below. Each need two forks to start eating. They need to share these forks so that each can eat.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/442/0*I5742bvegM6I0Qhy.png" /></figure><p>The code given below causes deadlock. As each philosophers hold one fork and not able to grab another.</p><pre>#include &lt;iostream&gt;<br>#include &lt;thread&gt;<br>#include &lt;mutex&gt;<br>#include &lt;vector&gt;<br>#include &lt;string&gt;<br>#include &lt;chrono&gt;<br><br>using namespace std::literals;<br><br>constexpr int nforks = 5;<br>constexpr int nphilosophers = nforks;<br>std::string names[nphilosophers] = {&quot;A&quot;, &quot;B&quot;, &quot;C&quot;, &quot;D&quot;, &quot;E&quot;};<br><br>// Keep track of how many times a philosopher is able to eat<br>int mouthfuls[nphilosophers] = {0};<br>constexpr auto think_time = 2s;<br>constexpr auto eat_time = 1s;<br><br>// A mutex prevents more than one philosopher picking up the same fork<br>std::mutex fork_mutex[nforks];<br><br>// Mutex to protect output<br>std::mutex print_mutex;<br><br>// Functions to display information about the &#39;nth&#39; philosopher<br><br>// Interactions with a fork<br>void print(int n, const std::string&amp; str, int forkno)<br>{<br> std::lock_guard&lt;std::mutex&gt; print_lock(print_mutex);<br> std::cout &lt;&lt; &quot;Philosopher &quot; &lt;&lt; names[n] &lt;&lt; str &lt;&lt; forkno &lt;&lt; &#39;\n&#39;;<br>}<br><br>// The philosopher&#39;s state<br>void print(int n, const std::string&amp; str)<br>{<br> std::lock_guard&lt;std::mutex&gt; print_lock(print_mutex);<br> std::cout &lt;&lt; &quot;Philosopher &quot; &lt;&lt; names[n] &lt;&lt; str &lt;&lt; &#39;\n&#39;;<br>}<br><br>// Thread which represents a dining philosopher<br>void dine(int phil_no)<br>{<br> int lfork = phil_no;<br> int rfork = (phil_no+1) % nforks;<br> <br> print(phil_no, &quot;\&#39;s left fork is number &quot;, lfork);<br> print(phil_no, &quot;\&#39;s right fork is number &quot;, rfork);<br> print(phil_no, &quot; is thinking...&quot;);<br><br> std::this_thread::sleep_for(think_time);<br><br> // Make an attempt to eat<br> print(phil_no, &quot; reaches for fork number &quot;, lfork);<br><br> // Try to pick up the left fork<br> fork_mutex[lfork].lock();<br> print(phil_no, &quot; picks up fork &quot;, lfork);<br> print(phil_no, &quot; is thinking...&quot;);<br><br> // Succeeded - now try to pick up the right fork<br> std::this_thread::sleep_for(think_time);<br><br> print(phil_no, &quot; reaches for fork number &quot;, rfork);<br><br> fork_mutex[rfork].lock();<br><br> // Succeeded - this philosopher can now eat<br> print(phil_no, &quot; picks up fork &quot;, rfork);<br> print(phil_no, &quot; is eating...&quot;);<br> mouthfuls[phil_no]++;<br> std::this_thread::sleep_for(eat_time);<br><br> print(phil_no, &quot; puts down fork &quot;, lfork);<br> print(phil_no, &quot; puts down fork &quot;, rfork);<br> print(phil_no, &quot; is thinking...&quot;);<br><br> fork_mutex[lfork].unlock();<br> fork_mutex[rfork].unlock();<br> std::this_thread::sleep_for(think_time);<br>}<br><br>int main()<br>{<br> // Start a separate thread for each philosopher<br> std::vector&lt;std::thread&gt; philos;<br><br> for (int i = 0; i &lt; nphilosophers; ++i) {<br>  philos.push_back(std::move(std::thread{dine, i}));<br> }<br><br> for (auto&amp; philo: philos)<br>  philo.join();<br><br> // How many times were the philosophers able to eat?<br> for (int i = 0; i &lt; nphilosophers; ++i) {<br>  std::cout &lt;&lt; &quot;Philosopher &quot; &lt;&lt; names[i];<br>  std::cout &lt;&lt; &quot; had &quot; &lt;&lt; mouthfuls[i] &lt;&lt; &quot; mouthfuls\n&quot;;<br> }<br>}</pre><p><strong>Setting hierarchy of mutexes</strong>: One possible solution to above problem is setting order in which mutexes can be picked. One of the order could be to always pick lower index mutex first. If philosopher-2 need fork-2 and fork-3, he needs to pick fork-2 first. Similarly, philosopher-5 need fork-1 and fork-5, he needs to pick fork-1 first.</p><p>We can add below code in dine() function after setting value of lfork and rfork. Other lines remain same. This makes sure that fork with lower indexes are picked first.</p><pre>void dine(int phil_no)<br>{<br>   int lfork = phil_no;<br>   int rfork = (phil_no+1) % nforks;<br><br>   if(lfork &gt; rfork) {<br>     std::swap(lfork, rfork);<br>   }<br>   <br>   //....... remain same as above<br> <br>}</pre><p><strong>Using std::lock: </strong>Another possible solution is to use std::lock. We will grab both the forks needed together. Below we have rewritten dine() function with std::lock().</p><pre>void dine(int phil_no)<br>{<br> int lfork = phil_no;<br> int rfork = (phil_no+1) % nforks;<br><br> std::this_thread::sleep_for(think_time);<br><br> std::lock(fork_mutex[lfork], fork_mutex[rfork]);<br> std::this_thread::sleep_for(think_time);<br> mouthfuls[phil_no]++;<br> std::this_thread::sleep_for(eat_time);<br><br> fork_mutex[lfork].unlock();<br> fork_mutex[rfork].unlock();<br> std::this_thread::sleep_for(think_time);<br>}</pre><h3>Livelock:</h3><p>In both deadlock and livelock cases, program cannot make progress.</p><ul><li>In deadlock, the threads are inactive.</li><li>In livelock, the threads are still active.</li></ul><p>Livelock can result from badly done deadlock avoidance.</p><ul><li>A thread cannot get a lock.</li><li>Instead of blocking indefinitely, it backs off and tries again.</li></ul><p>Here is an example of live lock where:</p><ul><li>thread-1 locks mutex-1 and then tries to lock mutex-2</li><li>thread-2 locks mutex-2 and then tries to lock mutex-1</li></ul><pre>#include &lt;mutex&gt;<br>#include &lt;thread&gt;<br>#include &lt;iostream&gt;<br><br>using namespace std::chrono_literals;<br><br>std::mutex m1,m2;<br><br>void funcA(){<br> bool locked = false;<br> while(!locked){<br>  std::lock_guard&lt;std::mutex&gt; lg(m1);<br>  std::this_thread::sleep_for(2s);<br>  locked = m2.try_lock();<br> }<br> if(locked){<br>  std::cout&lt;&lt;&quot;Thread 1 acquired both mutexes\n&quot;;<br> }<br>}<br><br>void funcB(){<br> bool locked = false;<br> while(!locked){<br>  std::lock_guard&lt;std::mutex&gt; lg(m2);<br>  std::this_thread::sleep_for(2s);<br>  locked = m1.try_lock();<br> }<br> if(locked){<br>  std::cout&lt;&lt;&quot;Thread 2 acquired both mutexes\n&quot;;<br> }<br>}<br><br><br>int main(){<br> std::thread t1(funcA);<br> std::thread t2(funcB);<br><br> t1.join();<br> t2.join();<br><br> std::cout&lt;&lt;&quot;Main thread finished\n&quot;;<br> return 0;<br>}</pre><p>This is an example of livelock where both threads are running, but program cannot make any progress because while-loop never breaks.</p><p>We can use std::scoped_lock to fix this problem. std::scoped_lock locks all provided mutexes together.</p><pre>#include &lt;mutex&gt;<br>#include &lt;thread&gt;<br>#include &lt;iostream&gt;<br><br>using namespace std::chrono_literals;<br><br>std::mutex m1,m2;<br><br>void funcA(){<br> std::scoped_lock lock(m1, m2);<br> std::cout&lt;&lt;&quot;Thread 1 acquired both mutexes\n&quot;;<br>}<br><br>void funcB(){<br> std::scoped_lock lock(m2, m1);<br> std::cout&lt;&lt;&quot;Thread 2 acquired both mutexes\n&quot;;<br>}<br><br><br>int main(){<br> std::thread t1(funcA);<br> std::thread t2(funcB);<br><br> t1.join();<br> t2.join();<br><br> std::cout&lt;&lt;&quot;Main thread finished\n&quot;;<br> return 0;<br>}<br></pre><p><strong>Reference</strong>: <a href="https://www.udemy.com/course/learn-modern-cplusplus-concurrency/?couponCode=NVDIN35">https://www.udemy.com/course/learn-modern-cplusplus-concurrency</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e24af312e0be" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Multithreading in C++. Part-3]]></title>
            <link>https://hksoni.medium.com/multithreading-in-c-part-3-e858872625a6?source=rss-9be79c07dba------2</link>
            <guid isPermaLink="false">https://medium.com/p/e858872625a6</guid>
            <category><![CDATA[cpp-programming]]></category>
            <category><![CDATA[multithreading]]></category>
            <dc:creator><![CDATA[Harish Kant Soni]]></dc:creator>
            <pubDate>Sun, 30 Mar 2025 18:23:07 GMT</pubDate>
            <atom:updated>2025-03-30T18:23:07.288Z</atom:updated>
            <content:encoded><![CDATA[<h4>Managing a thread:</h4><p>Detaching a thread : Instead of calling join() we can call detach(). The parent thread continue to execute, the child thread continues until it completes or program terminates. It is analogous to daemon process. Parent thread object is no longer associated with it. When thread goes out of scope, its will not call std::terminate if it was detached.</p><p>Parent thread throwing exception: Destructor are called for every object in scope including std::thread object. The destructor will check if join() or detach() is called or not. If not called, it will call std::terminate. So we must call call join() or detach() before a thread gets destroyed in all paths through the code.</p><p>What’s the issue in the given code:</p><pre>#include &lt;stdio.h&gt;<br>#include&lt;iostream&gt;<br>#include&lt;thread&gt;<br>int main()<br>{<br>    try{<br>        std::thread t([](){std::cout&lt;&lt;&quot;Hello world&quot;;});<br>        throw std::exception();<br>        t.join();<br>    }<br>    catch(std::exception&amp; e){<br>        std::cout&lt;&lt;&quot;Exception caught : &quot;&lt;&lt; e.what()&lt;&lt;&#39;\n&#39;;<br>    }<br><br>    return 0;<br>}</pre><p>In the code above, an exception is thrown before thread object t called join(). This leads to call std::terminate when t goes out of scope.</p><p>As a solution, we can call join() on the thread object in the catch block.</p><pre>int main()<br>{<br>    std::thread t([](){std::cout&lt;&lt;&quot;Hello world&quot;;});<br>    try{<br>        <br>        throw std::exception();<br>        t.join();<br>    }<br>    catch(std::exception&amp; e){<br>        std::cout&lt;&lt;&quot;Exception caught : &quot;&lt;&lt; e.what()&lt;&lt;&#39;\n&#39;;<br>        t.join();<br>    }<br><br>    return 0;<br>}</pre><p>As an another solution, we can use RAII. We can create a class which wraps std::thread object. This class’s destructor calls join() on wrapped std::thread object. A thread cab be joined only once, so we need to use joinable() which returns false if join() or detach() has been called on the wrapped thread otherwise true.</p><pre>class Thread_guard{<br>    std::thread thr;<br>    <br>    public:<br>    explicit Thread_guard(std::thread&amp;&amp; thr):thr(std::move(thr)){}<br>    ~Thread_guard(){<br>        if(thr.joinable())<br>            thr.join();<br>    }<br>    Thread_guard(const Thread_guard&amp;) = delete;<br>    Thread_guard&amp; operator= (const Thread_guard&amp;) = delete;<br>};<br><br>int main()<br>{<br>    try{<br>        std::thread t([](){std::cout&lt;&lt;&quot;Hello world&quot;;});<br>        Thread_guard t_grd(std::move(t));<br>        throw std::exception();<br>        t.join();<br>    }<br>    catch(std::exception&amp; e){<br>        std::cout&lt;&lt;&quot;Exception caught : &quot;&lt;&lt; e.what()&lt;&lt;&#39;\n&#39;;<br>    }<br><br>    return 0;<br>}</pre><h3>Working with Shared data:</h3><p><strong><em>Critical Section</em></strong>: A region of the code which must be executed by one thread at a time. Usually this involves accessing a shared resource.</p><p><strong><em>Mutex</em></strong>: are mutual exclusion objects. A mutex has two states. It can be locked or unlocked. If mutex is unlocked, one thread can enter the critical section. If it is locked no thread can enter the critical section. They have to wait until mutex in unlocked. A thread locks the mutex when it enters into a critical section and unlocks the mutex when is leaves the critical section.</p><p><strong><em>mutex class</em></strong>: C++ provides std::mutex class which can be used to synchronize threads. It has three methods lock(), try_lock(), unlock().</p><pre>#include &lt;iostream&gt;<br>#include &lt;thread&gt;<br>#include &lt;mutex&gt;<br><br>using namespace std::chrono_literals;<br><br>std::mutex mtx;<br><br>void task1(){<br>    mtx.lock();<br>    std::this_thread::sleep_for(500ms);<br>    mtx.unlock();<br>}<br><br>void task2(){<br>    std::this_thread::sleep_for(100ms);<br>    while(!mtx.try_lock()){<br>        std::this_thread::sleep_for(100ms);    <br>    }<br>    mtx.unlock();<br>}<br><br>int main(){<br>    std::thread t1(task1);<br>    std::thread t2(task2);<br>    <br>    t1.join();<br>    t2.join();<br><br>    return 0;<br>}</pre><p>In above example, thread t1 locks the mutex and thread t2 try_lock() it until it is able to lock.</p><p><strong><em>Internal Synchronization</em></strong>: When multiple threads access same memory location, we need to synchronize the data access to prevent data race. This is true for container as well. If we use extremal mutex, we call it external synchronization. If we include std::mutex as a data member of container class, we call it internal synchronization. Here is a minimal version of thread safe vector.</p><pre>class Vector{<br>    std::mutex mtx;<br>    std::vector&lt;int&gt; vec;<br>    <br>    public:<br>    void push_back(const int&amp; i){<br>        mtx.lock();<br>        vec.push_back(i);<br>        mtx.unlock();<br>    }<br>};</pre><p><strong><em>Lock Guard</em></strong>:</p><pre>std::mutex mtx;<br><br>void someFunc(){<br>    try{<br>        mtx.lock();<br>        <br>        // critical section throws exception<br>        <br>        mtx.unlock();<br>    }catch(std::exception&amp; e){<br>        <br>    }<br>}</pre><p>In the example above, when an exception is thrown in the critical section, mutex object does not get unblocked and left in the locked state. When exception in thrown:</p><ul><li>The destructors are called for all objects in scope.</li><li>The program flow jumps into the catch handler.</li><li>The unlock call is never executed.</li><li>The mutex remain locked.</li></ul><p>All threads which are waiting to lock the mutex are blocked.</p><p>This a drawback of using std::mutex class. Calling lock() requires a corresponding call to unlock(), unlock() must always be called even when there are multiple paths through critical section or an exception is thrown. It relies on the programmer to get it right. For these reason, we do not normally use std::mutex directly.</p><p>C++ standard library provides some wrapper classes which takes std::mutex as private data member and uses RAII idiom. The constructor locks the mutex and destructor unlocks the mutex. We create the wrapper class object on stack. When object goes out of scope, destructor is called and object is mutex is unlocked. This happens automatically, even if exception is thrown.</p><p><strong><em>std::lock_guard</em></strong> : This is a very basic wrapper. It has a constructor and a destructor only. The constructors takes a mutex as an argument. Initializes its member from the argument and locks it. Its destructor unlocks the mutex. std::lock_guard is a template class, we need to provide type of the mutex as the template parameter. In C++17, constructors can deduce the type of template parameters, we can skip it.</p><pre>std::mutex mtx;<br><br>void func(){<br>    for(int i=0;i&lt;5;i++){<br>        std::lock_guard lg(mtx);<br>        // critical section<br>        // do something here on shared resources.<br>        // end of critical section<br><br>        // code after critical section<br>    }<br>}</pre><p>In above example, we lock some shared resource 5 times and it gets unlocked automatically using std::lock_guard.</p><p><strong><em>std::unique_lock</em></strong>: When we use std::lock_guard, any code which is executed after critical section which does not access any shared resources, still runs while mutex is locked. This forces other threads to wait until destructor of std::lock_guard is called. If we call unlock() on the mutex after the critical section, unlock() will again be called in the destructor of std::lock_guard. This will crash the program.</p><p>std::unique_lock solves this problem. This has all the features of std::lock_guard and it has unlock() function. We can call this function after the critical section. This avoids blocking other threads while we execute non-critical code. If we do not unblock(), the destructor will unblock the mutex. This ensures that the lock is always released.</p><pre>#include &lt;iostream&gt;<br>#include &lt;mutex&gt;<br>#include &lt;thread&gt;<br><br>using namespace std::literals;<br>std::mutex print_mutex;<br><br>void task(std::string str){<br>    for(int i=0; i&lt;5;i++){<br>        std::unique_lock&lt;std::mutex&gt; ul(print_mutex);<br>        // std::cout is critical section<br>        std::cout&lt;&lt;str[0]&lt;&lt;str[1]&lt;&lt;str[2]&lt;&lt;std::endl;<br>        // end of critical section<br>        ul.unlock();<br>        std::this_thread::sleep_for(500ms);<br>    }<br>}<br><br>int main()<br>{<br>    std::thread t1(task,&quot;abc&quot;);<br>    std::thread t2(task,&quot;xyz&quot;);<br>    std::thread t3(task,&quot;123&quot;);<br>    <br>    t1.join();<br>    t2.join();<br>    t3.join();<br><br>    return 0;<br>}</pre><p>In the above example, std::cout is critical section. If we comment out ul.unlock(); , we will see significant drop in the performance. This happens because other threads cannot enter the critical section until ul object is destroyed. However, ul.unlock(); releases the mutex after critical section is over. It does not wait for ul object to go out of scope to make mutex free.</p><p>We can pass optional second argument to std::unique_lock constructor to change its behavior.</p><p><strong>std::try_to_lock</strong> : Calls the mutex’s try_lock() member function. The owns_lock() member function checks if the mutex is locked.</p><p><strong>std::defer_lock</strong> : Does not lock the mutex. Can lock it later by calling lock() member function or by passing std::unique_lock object to std::lock().</p><p><strong>std::adopt_lock</strong> : Takes a mutex that is already locked. Avoids locking the mutex twice.</p><p>std::unique_lock is move only class.</p><p>std::unique_lock vs std::lock_guard : std::unique_lock has more features than std::lock_guard . Use std::lock_guard when we need lock for the entire scope. Use std::unique_lock when you need to unblock the mutex somewhere in between.</p><p><strong>Timeouts and Mutexes </strong>: If a thread has locked a mutex, it should not lock is again until it’s unlocked. Calling lock() twice on a mutex is undefined. There is std::recursive_mutex which can be locked multiple times without calling unlock. For each lock() call there must be eventually an unblock() call otherwise no other thread will be able to lock() this mutex. There are not many cases where std::recursive_mutex is needed. Here we will try to demonstrate its use by a bad example.</p><pre>#include &lt;iostream&gt;<br>#include &lt;thread&gt;<br>#include &lt;mutex&gt;<br><br>std::mutex mtx;<br><br>int bad_fact(int i){<br>    if(i==1){<br>        return 1;<br>    }<br>    mtx.lock();<br>    int b = i*bad_fact(i-1);<br>    std::cout&lt;&lt;b&lt;&lt;std::endl;<br>    mtx.unlock();<br>    return b;<br>}<br><br>int main()<br>{<br>    std::thread t1(bad_fact,5);<br>    std::thread t2(bad_fact,7);<br>    <br>    t1.join();<br>    t2.join();<br><br>    return 0;<br>}</pre><p>This code gives run time error because we are trying to lock the same mutex again in recursive calls. However, if we use std::recursive_mutex, this works fine.</p><p>Above example can also be rewritten using std::lock_guard.</p><pre>std::recursive_mutex mtx;<br><br>int bad_fact(int i){<br>    if(i==1){<br>        return 1;<br>    }<br>    std::lock_guard&lt;std::recursive_mutex&gt; lg(mtx);<br>    int b = i*bad_fact(i-1);<br>    std::cout&lt;&lt;b&lt;&lt;std::endl;<br>    return b;<br>}</pre><p>std::timed_mutex : It is same as std::mutex, but with extra capabilities. We have already seen try_lock() methods of std::mutex , this have zero timeout as it returns instantly. You can think of lock() methods has timeout as infinity because it does not return until the mutex is locked.</p><p>Sometimes we want something which has finite timeout and not as extreme as try_lock() or lock().</p><ul><li>try_lock_for() : Keep trying to lock the mutex for a specified duration.</li><li>try_lock_until() : Keep trying to lock the mutex until a spcified time.</li></ul><p>Both of the above functions return bool. True if lock was acquired false otherwise.</p><p>These two functions are requests. They are not hard, rigid, realtime deadlines. It is possible that these functions may return later than you expected, but never early.</p><p>std::recursive_timed_mutex : It has 4 self explanatory functions and it can be used similarly to std::recursive_mutex.</p><ul><li>lock()</li><li>unlock()</li><li>try_lock()</li><li>try_lock_for()</li><li>try_lock_until()</li></ul><pre>#include &lt;iostream&gt;<br>#include &lt;thread&gt;<br>#include &lt;mutex&gt;<br>#include &lt;chrono&gt;<br><br>using namespace std::literals;<br>std::timed_mutex t_mutex;<br><br>void task1(){<br>    std::cout&lt;&lt;&quot;Task1 trying to get lock\n&quot;;<br>    t_mutex.lock();<br>    std::cout&lt;&lt;&quot;Task1 locks lock the mutex\n&quot;;<br>    std::this_thread::sleep_for(5s);<br>    std::cout&lt;&lt;&quot;Task1 unlocking the mutex\n&quot;;<br>    t_mutex.unlock();<br>}<br><br>void task2(){<br>    std::this_thread::sleep_for(500ms);<br>    std::cout&lt;&lt;&quot;Task2 trying to lock the mutex\n&quot;;<br>    <br>    auto deadline = std::chrono::system_clock::now() + 900ms;<br>    while(!t_mutex.try_lock_until(deadline)){<br>        deadline = std::chrono::system_clock::now() + 900ms;<br>        std::cout&lt;&lt;&quot;Task2 could not lock the mutex\n&quot;;<br>    }<br>    <br>    std::cout&lt;&lt;&quot;Task2 has locked the mutex\n&quot;;<br>    t_mutex.unlock();<br>}<br><br>int main()<br>{<br>    std::thread t1(task1);<br>    std::thread t2(task2);<br>    <br>    t1.join();<br>    t2.join();<br><br>    return 0;<br>}<br><br>// ***************output*****************<br>// Task1 trying to get lock<br>// Task1 locks lock the mutex<br>// Task2 trying to lock the mutex<br>// Task2 could not lock the mutex<br>// Task2 could not lock the mutex<br>// Task2 could not lock the mutex<br>// Task2 could not lock the mutex<br>// Task1 unlocking the mutex<br>// Task2 has locked the mutex</pre><p>std::unique_lock() also has try_lock_for() and try_lock_until() member functions which are forwarded to the wrapped mutex. The code will compile only if the wrapped mutex supports these functions.</p><p>We can rewrite above code using std::lock_guard and std::unique_lock in this way:</p><pre>#include &lt;iostream&gt;<br>#include &lt;thread&gt;<br>#include &lt;mutex&gt;<br>#include &lt;chrono&gt;<br><br>using namespace std::literals;<br>std::timed_mutex t_mutex;<br><br>void task1(){<br>    std::cout&lt;&lt;&quot;Task1 trying to get lock\n&quot;;<br>    std::lock_guard&lt;std::timed_mutex&gt; lg(t_mutex);<br>    std::cout&lt;&lt;&quot;Task1 locks lock the mutex\n&quot;;<br>    std::this_thread::sleep_for(5s);<br>    std::cout&lt;&lt;&quot;Task1 unlocking the mutex\n&quot;;<br>}<br><br>void task2(){<br>    std::this_thread::sleep_for(500ms);<br>    std::cout&lt;&lt;&quot;Task2 trying to lock the mutex\n&quot;;<br>    <br>    std::unique_lock&lt;std::timed_mutex&gt; ul(t_mutex, std::defer_lock);<br>    <br>    auto deadline = std::chrono::system_clock::now() + 900ms;<br>    while(!ul.try_lock_until(deadline)){<br>        deadline = std::chrono::system_clock::now() + 900ms;<br>        std::cout&lt;&lt;&quot;Task2 could not lock the mutex\n&quot;;<br>    }<br>    <br>    std::cout&lt;&lt;&quot;Task2 has locked the mutex\n&quot;;<br>}<br><br>int main()<br>{<br>    std::thread t1(task1);<br>    std::thread t2(task2);<br>    <br>    t1.join();<br>    t2.join();<br><br>    return 0;<br>}</pre><p><strong>std::chrono Clocks</strong> :</p><ul><li>chrono::system_clock : It gets time on OS. It may change erratically if your program in executing during daylight saving or leap year. It can also get affected when system clock is running fast/slow and gets adjusted. This is used for time points. If we want something to happen by midday as seen by the system, we would use system clock.</li><li>chrono:steady_clock : It always increases steadily. Is never jumps around. It is used for measuring intervals. If you want to know how long your thread or part of code took to execute, you can use it.</li></ul><p><strong>Multiple Reader, Single Writer</strong> : Financial data feed generally has more readers than writers. As an example, many stock brokers and news outlets read stock prices frequently, but only a few transactions modifies it. This is one of the example or a few write accesses and many read accesses.</p><p>We must avoid data races. However, in scenarios involving multiple readers and a single writer, there is a high probability of multiple readers accessing the critical section concurrently. Since readers do not modify the data in the critical section, their simultaneous access does not cause a data race. We do not need to synchronize shared data access in this case.</p><p>When a writer thread needs to access the critical section, it is essential to block access for all other reader and writer threads. This ensures the shared data in the critical section remains consistent and is not modified until the writer thread completes its work.</p><p>With std::mutex, all threads are synchronized. They must execute their critical section sequentially even when it is not necessary like multiple reader thread scenario. This affects the performance of the program.</p><pre>#include &lt;iostream&gt;<br>#include &lt;shared_mutex&gt;<br>#include &lt;thread&gt;<br>#include &lt;chrono&gt;<br>#include &lt;vector&gt;<br><br>using namespace std::literals;<br><br>std::mutex mtx;<br><br>//shared variable<br>int x = 0;<br><br>void writer(){<br>    std::lock_guard&lt;std::mutex&gt; lg(mtx);<br>    //critical section start<br>    ++x;<br>    //critical section end<br>}<br><br>void reader(){<br>    std::lock_guard&lt;std::mutex&gt; lg(mtx);<br>    // Critical section reading take 100ms<br>    std::this_thread::sleep_for(100ms);<br>}<br><br>int main()<br>{<br>    std::vector&lt;std::thread&gt; v;<br>    <br>    auto start = std::chrono::steady_clock::now();<br>    <br>    for(int i=0;i&lt;20;i++){<br>        v.push_back(std::thread(reader));<br>    }<br>    <br>    v.push_back(std::thread(writer));<br>    v.push_back(std::thread(writer));<br>    <br>    for(int i=0;i&lt;20;i++){<br>        v.push_back(std::thread(reader));<br>    }<br>    <br>    for(auto&amp; th:v){<br>        th.join();<br>    }<br>    auto end = std::chrono::steady_clock::now();<br>    auto duration = std::chrono::duration_cast&lt;std::chrono::milliseconds&gt;(end - start);<br>    std::cout &lt;&lt; &quot;Execution time: &quot; &lt;&lt; duration.count() &lt;&lt; &quot; milliseconds&quot; &lt;&lt; std::endl;<br>    return 0;<br>}<br>// *************output************<br>// Execution time: 4010 milliseconds</pre><p>In the above example, we have a writer and a reader thread. There is an integer x which represent shared data in the program. Writer thread updated the shared data while reader thread takes about 100ms to read the shared data. We are using std::mutex to synchronize access to the critical section. There are total 40 reader and 2 writer threads. The reader threads are going to take 40 * 100ms = 4000ms = 4s to execute. This does not include time taken by writer threads. <br>If we allow all reader threads to access the shared data concurrently, in the best case, they may be able to finish their task in 100ms. This happens because every thread is going to take 100ms and they are not running sequentially.</p><p>It would be useful to have “selective” locking.</p><ul><li>Lock when there is a thread which is writing.</li><li>Do not lock when there are only reading threads.</li><li>Often called a “read-write lock”.</li></ul><p><strong>std::shared_mutex</strong> : It is defined in &lt;shared_mutex&gt; header file. It can be locked in two different ways:</p><ul><li>Exclusive lock:<br>- No other thread may acquire a lock.<br>- No other thread can enter a critical section.</li><li>Shared lock:<br>- Other threads may acquire a shared lock.<br>- They can execute critical section concurrently</li></ul><p>To obtain an exclusive lock, we use :</p><ul><li>std::lock_guard&lt;std::shared_mutex&gt;</li><li>std::unique_lock&lt;std::shared_mutex&gt;</li></ul><p>We can pass shared_mutex object as constructor argument in the above two mutex wrappers. This creates an object in which the shared mutex has an exclusive lock. A thread can only acquire an exclusive lock when the mutex is unlocked. If there are other threads which have locks, either shared or exclusive, then this thread must wait.</p><p>To obtain a shared lock, we use:</p><ul><li>std::shared_lock&lt;std::shared_mutex&gt;</li></ul><p>This created a shared_lock object, where the mutex has a shared lock. A thread which has shared lock, can enter a critical section. It can only acquire this shared lock if there are no threads which have exclusive locks. If there is a thread which has exclusive lock, the the thread have to wait that thread releases the exclusive lock.</p><p>Above example can be rewritten with shared_lock in this way:</p><pre>#include &lt;iostream&gt;<br>#include &lt;shared_mutex&gt;<br>#include &lt;thread&gt;<br>#include &lt;chrono&gt;<br>#include &lt;vector&gt;<br><br>using namespace std::literals;<br><br>std::shared_mutex mtx;<br><br>//shared variable<br>int x = 0;<br><br>void writer(){<br>    std::lock_guard&lt;std::shared_mutex&gt; lg(mtx);<br>    //critical section start<br>    ++x;<br>    //critical section end<br>}<br><br>void reader(){<br>    std::shared_lock&lt;std::shared_mutex&gt; lg(mtx);<br>    // Critical section reading take 100ms<br>    std::this_thread::sleep_for(100ms);<br>}<br><br>int main()<br>{<br>    std::vector&lt;std::thread&gt; v;<br>    <br>    auto start = std::chrono::steady_clock::now();<br>    <br>    for(int i=0;i&lt;20;i++){<br>        v.push_back(std::thread(reader));<br>    }<br>    <br>    v.push_back(std::thread(writer));<br>    v.push_back(std::thread(writer));<br>    <br>    for(int i=0;i&lt;20;i++){<br>        v.push_back(std::thread(reader));<br>    }<br>    <br>    for(auto&amp; th:v){<br>        th.join();<br>    }<br>    auto end = std::chrono::steady_clock::now();<br>    auto duration = std::chrono::duration_cast&lt;std::chrono::milliseconds&gt;(end - start);<br>    std::cout &lt;&lt; &quot;Execution time: &quot; &lt;&lt; duration.count() &lt;&lt; &quot; milliseconds&quot; &lt;&lt; std::endl;<br>    return 0;<br>}<br>// *************output************<br>// Execution time: 101 milliseconds</pre><p>As we can see, without shared_lock, it took 4010ms to execute the program while with shared_lock in reader threads, it took just 101ms.</p><p>std::shared_mutex <strong>member functions</strong> :</p><ul><li>Exclusive locking:<br>- lock()<br>- try_lock()<br>- unlock()</li><li>Shared locking:<br>- lock_shared()<br>- try_lock_shared()<br>- unlock_shared()</li></ul><p>These are needed when you are forced to use std::shared_mutex directly without any wrapper like std::lock_guard, std::unique_lock and std::shared_lock.</p><p><strong>Pro and Cons of std::shared_mutex</strong>:</p><ul><li>Use more memory that std::mutex</li><li>Slower than std::mutex</li><li>Best suited for situations where:<br>- Reader threads greatly outnumber writer threads.<br>- Read operations take a long time.</li></ul><p><strong>Shared data Initialization:</strong></p><p>Shared data can take a variety of forms.</p><ul><li>Global variable: Accessible to all code in the program.</li><li>Static Variable at namespace scope: Accessible to all code in the translation unit.</li><li>Class member declared static: Potentially accessible to code which calls its member functions. If public, accessible to all code.</li><li>Local variable declared static: Accessible to all code which calls that function.</li></ul><p>In terms of initialization, first 3 variable types are initialized when the program starts up, before main() function is called. At that point, only one thread would be running and there cannot be a data race.</p><p>For the static local variable, it is a little bit more involved. The initialization takes place when the program is running and this occurs when the program reaches the declaration for the first time.</p><pre>void func(){<br>    //some code<br>    std::string s(&quot;xyz&quot;);<br>    // some code<br>}</pre><p>In above program, first time when program reaches declaration of string s, it will call the constructor. In multithreaded program, if multiple threads try to call the constructor concurrently, can there be data race ?</p><p>From C++11 onwards, local static variables initialization:</p><ul><li>Only one thread can initialize local static variables.</li><li>Any other thread that reaches the declaration is blocked.</li><li>It has to wait until the first thread has finished initializing the variable.</li><li>The threads are synchronized by the implementation.</li><li>No data race.</li></ul><p>Subsequent modifications:</p><ul><li>The usual rules for shared data.</li><li>There will be data race, unless we protect against one.</li></ul><p><strong>Singleton Design pattern</strong>: This pattern uses the concept of local static variable initialization mentioned above.</p><pre>#include&lt;iostream&gt;<br>#include&lt;thread&gt;<br>#include&lt;vector&gt;<br><br>class Singleton<br>{<br>public:<br>    static Singleton &amp;getInstance()<br>    {<br>        static Singleton instance; // Static local variable<br>        std::cout &lt;&lt; &quot;Address of instance is &quot;&lt;&lt; &amp;instance &lt;&lt; std::endl;<br>        return instance;<br>    }<br><br>    void doSomething()<br>    {<br>        std::cout &lt;&lt; &quot;Singleton doing something...&quot; &lt;&lt; std::endl;<br>    }<br><br>private:<br>    Singleton() {}                                    // Private constructor to prevent instantiation<br>    Singleton(const Singleton &amp;) = delete;            // Delete copy constructor<br>    Singleton &amp;operator=(const Singleton &amp;) = delete; // Delete assignment operator<br>};<br><br>int main()<br>{<br>    std::vector&lt;std::thread&gt; v;<br>    for(int i = 0;i&lt;5;i++){<br>        v.push_back(std::thread(Singleton::getInstance));<br>    }<br>    for(auto &amp;th:v){<br>        th.join();<br>    }<br><br>    return 0;<br>}<br>// ****************output**************<br>// Address of instance is 0x56635e355151<br>// Address of instance is 0x56635e355151<br>// Address of instance is 0x56635e355151<br>// Address of instance is 0x56635e355151<br>// Address of instance is 0x56635e355151</pre><p>In the above example, getInstance() is called by 5 threads, but the address of the object created it same. This is because static local variable initialization is done by first thread executing the line and other threads are blocked meanwhile.</p><p><strong>Thread local variable</strong>:</p><p>A <strong>thread-local variable</strong> in C++ is a variable that is unique to each thread. Each thread has its own separate instance of the variable, meaning changes made by one thread do not affect the value seen by other threads.</p><p><strong>How to Declare Thread-Local Variables:</strong></p><p>You use the thread_local storage class specifier to declare a thread-local variable.</p><p>Example 1: Basic Thread-Local Variable</p><pre>#include &lt;iostream&gt;<br>#include &lt;thread&gt;<br><br>// Thread-local variable<br>thread_local int thread_local_var = 0;<br><br>void incrementAndPrint(const std::string&amp; threadName) {<br>    ++thread_local_var; // Increment the thread-local variable<br>    std::cout &lt;&lt; threadName &lt;&lt; &quot;: thread_local_var = &quot; &lt;&lt; thread_local_var &lt;&lt; std::endl;<br>}<br><br>int main() {<br>    std::thread t1(incrementAndPrint, &quot;Thread 1&quot;);<br>    std::thread t2(incrementAndPrint, &quot;Thread 2&quot;);<br><br>    t1.join();<br>    t2.join();<br><br>    return 0;<br>}<br>// ************output*************<br>// Thread 1: thread_local_var = 1<br>// Thread 2: thread_local_var = 1</pre><p>Each thread starts with its own instance of thread_local_var initialized to 0. Incrementing it in one thread does not affect the other thread&#39;s instance.</p><p><strong>Key Points:</strong></p><ul><li>Scope and Lifetime:<br>- A thread_local variable is local to each thread.<br>- It persists for the entire lifetime of the thread.</li><li>Storage Class:<br>- The thread_local specifier can be used with global, static, or local variables.</li><li>Initialization:<br>- Each thread initializes its copy of the thread-local variable.</li></ul><p>Example 1: Basic Thread-Local Variable:</p><pre>#include &lt;iostream&gt;<br>#include &lt;thread&gt;<br><br>class MyClass {<br>public:<br>    static thread_local int threadLocalMember;<br>};<br><br>thread_local int MyClass::threadLocalMember = 10;<br><br>void modifyAndPrint(const std::string&amp; threadName) {<br>    MyClass::threadLocalMember += 5; // Modify thread-local member<br>    std::cout &lt;&lt; threadName &lt;&lt; &quot;: MyClass::threadLocalMember = &quot; <br>              &lt;&lt; MyClass::threadLocalMember &lt;&lt; std::endl;<br>}<br><br>int main() {<br>    std::thread t1(modifyAndPrint, &quot;Thread 1&quot;);<br>    std::thread t2(modifyAndPrint, &quot;Thread 2&quot;);<br><br>    t1.join();<br>    t2.join();<br><br>    return 0;<br>}<br>// **************output***************<br>// Thread 1: MyClass::threadLocalMember = 15<br>// Thread 2: MyClass::threadLocalMember = 15</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e858872625a6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Make files]]></title>
            <link>https://hksoni.medium.com/make-files-0e7b5cac7b7a?source=rss-9be79c07dba------2</link>
            <guid isPermaLink="false">https://medium.com/p/0e7b5cac7b7a</guid>
            <category><![CDATA[makefile]]></category>
            <dc:creator><![CDATA[Harish Kant Soni]]></dc:creator>
            <pubDate>Fri, 03 Jan 2025 06:09:14 GMT</pubDate>
            <atom:updated>2025-01-03T06:12:11.989Z</atom:updated>
            <content:encoded><![CDATA[<p>A simple makefile consists of “rules” with the following shape:</p><pre>target ... : prerequisites ...<br>    recipe<br>    ...<br>    ...</pre><p><strong>Target </strong>: A target is usually the name of a file that is generated by a program; examples of targets are executable or object files.</p><p><strong>Prerequisite </strong>: A prerequisite is a file that is used as input to create the target. A target often depends on several prerequisites. The prerequisites must exist before the target can be made successfully.</p><p><strong>Recipe/commands</strong> : A recipe/command is an action that make carries out to create the target from the prerequisites. A recipe may have more than one command, either on the same line or each on its own line.</p><p><em>Please note: you need to put a tab character at the beginning of every recipe line!</em></p><h3>A Simple Makefile:</h3><pre>hello: hello.cpp<br>  g++ hello.cpp -o hello</pre><p>Save above code in a Makefile in the same directory as hellp.cpp. To run it, type make from command prompt.</p><pre>$ make</pre><p>If a target is included as a command-line argument, that target is build. If no command-line targets are given, them the first target in the file is used, called the <em>default goal</em>.</p><p>To explain above line with an example, we can run above make file with this command</p><pre>$ make hello</pre><p>This is same as the above. In this case, we are explicitely telling make to build <em>hello </em>target. When we do not provide any target name first target is build.</p><p>Here is a rule for compiling a C file <em>foo.c</em> into an object file <em>foo.o</em>:</p><pre>foo.o: foo.c foo.h<br>  gcc -c foo.c</pre><p>Target : <em>foo.o</em></p><p>Prerequisites: <em>foo.c</em> and<em> foo.h</em></p><p>command: <em>gcc -c foo.c </em>(Please not that command is preceded by a tab character)</p><p>When <em>make </em>is asked to evaluate a rule, it begins by finding the files indicated by the prerequisites and the target for that rule. In the example above, we will run default target(<em>foo.o</em>) by running command from terminal:</p><p>$ make</p><p>Make will search for the target(foo.o) and prerequisites(<em>foo.c</em> and<em> foo.h</em>). If any of the prerequisites are also created by a rule, make will run that rule first.</p><p>Let’s take one more example:</p><pre>foo: foo.c<br> gcc -o foo foo.c<br><br>foo.c:<br> echo &quot;int main() { return 0; }&quot; &gt; foo.c</pre><p>In this example, <em>foo </em>target is created with prerequisite <em>foo.c</em>, but <em>foo.c</em> is also created using a rule. As we said earlier <em>If any of the prerequisites are created by a rule, make will run that rule first</em>.</p><p>When we run make command, it will try to create <em>foo </em>from <em>foo.c</em>, but first it has to create <em>foo.c</em> using the rule mentioned for it.</p><p>Now, after creating <em>foo.c</em>, target <em>foo </em>will be considered. A target is only build if:</p><ul><li>any of perquisites has newer timestamp than the target</li><li>if the target does not exist</li></ul><p>If any command generates an error, the building of the target is terminated and make exists.</p><p>Let’s take one more example. Here is a program to count the number of occurrences of the words “fee,” “fie,” “foe,” and “fum” in its input. It uses a flex scanner. Do not worry if you do not know flex scanner. Just follow the example.</p><p>Create these files in your directory:</p><p>.<br>├── count_words.c<br>├── lexer.l<br>└── Makefile</p><pre>// count_words.c<br>#include &lt;stdio.h&gt;<br>extern int fee_count, fie_count, foe_count, fum_count;<br>extern int yylex(void);<br>int main(int argc, char **argv) {<br>  yylex();<br>  printf(&quot;%d %d %d %d\n&quot;, fee_count, fie_count, foe_count, fum_count);<br>  exit(0);<br>}</pre><pre>// lexer.l<br>    int fee_count = 0;<br>    int fie_count = 0;<br>    int foe_count = 0;<br>    int fum_count = 0;<br>%%<br>fee fee_count++;<br>fie fie_count++;<br>foe foe_count++;<br>fum fum_count++;</pre><pre>count_words: count_words.o lexer.o -lfl<br> gcc count_words.o lexer.o -lfl -o count_words<br><br>count_words.o: count_words.c<br> gcc -c count_words.c<br><br>lexer.o: lexer.c<br> gcc -c lexer.c<br><br>lexer.c: lexer.l<br> flex -t lexer.l &gt; lexer.c</pre><p>Reference : Managing Projects with GNU Make by Robert Mecklenburg</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0e7b5cac7b7a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Passing overloaded functions in std::thread]]></title>
            <link>https://hksoni.medium.com/passing-overloaded-functions-in-std-thread-4853a9d9f46d?source=rss-9be79c07dba------2</link>
            <guid isPermaLink="false">https://medium.com/p/4853a9d9f46d</guid>
            <dc:creator><![CDATA[Harish Kant Soni]]></dc:creator>
            <pubDate>Tue, 03 Dec 2024 00:21:32 GMT</pubDate>
            <atom:updated>2024-12-03T00:21:32.820Z</atom:updated>
            <content:encoded><![CDATA[<p>In C++, you <strong>cannot directly pass the name of an overloaded function</strong> to a std::thread constructor because the compiler cannot resolve which version of the function you intend to use. To pass an overloaded function, you must explicitly disambiguate it.</p><p>Here’s how you can achieve it:</p><h3>1. Disambiguate with a Function Pointer</h3><p>You can pass a function pointer of the specific overload you want to call:</p><pre>#include &lt;iostream&gt;<br>#include &lt;thread&gt;<br><br>void print(int x) {<br>    std::cout &lt;&lt; &quot;Integer: &quot; &lt;&lt; x &lt;&lt; std::endl;<br>}<br><br>void print(const std::string&amp; str) {<br>    std::cout &lt;&lt; &quot;String: &quot; &lt;&lt; str &lt;&lt; std::endl;<br>}<br><br>int main() {<br>    // Resolve to the int overload<br>    std::thread t1(static_cast&lt;void (*)(int)&gt;(print), 42);<br><br>    // Resolve to the std::string overload<br>    std::thread t2(static_cast&lt;void (*)(const std::string&amp;)&gt;(print), &quot;Hello, world!&quot;);<br><br>    t1.join();<br>    t2.join();<br><br>    return 0;<br>}</pre><h3>2. Using Lambdas for Disambiguation</h3><p>Instead of relying on function pointers, you can use lambdas:</p><pre>#include &lt;iostream&gt;<br>#include &lt;thread&gt;<br><br>void print(int x) {<br>    std::cout &lt;&lt; &quot;Integer: &quot; &lt;&lt; x &lt;&lt; std::endl;<br>}<br><br>void print(const std::string&amp; str) {<br>    std::cout &lt;&lt; &quot;String: &quot; &lt;&lt; str &lt;&lt; std::endl;<br>}<br><br>int main() {<br>    // Pass specific overloads through lambdas<br>    std::thread t1([] { print(42); });<br>    std::thread t2([] { print(&quot;Hello, world!&quot;); });<br><br>    t1.join();<br>    t2.join();<br><br>    return 0;<br>}</pre><h3>3. Using std::bind</h3><p>std::bind can also be used to disambiguate overloaded functions:</p><pre>#include &lt;iostream&gt;<br>#include &lt;thread&gt;<br>#include &lt;functional&gt; // For std::bind<br><br>void print(int x) {<br>    std::cout &lt;&lt; &quot;Integer: &quot; &lt;&lt; x &lt;&lt; std::endl;<br>}<br><br>void print(const std::string&amp; str) {<br>    std::cout &lt;&lt; &quot;String: &quot; &lt;&lt; str &lt;&lt; std::endl;<br>}<br><br>int main() {<br>    // Resolve overloads using std::bind<br>    auto printInt = std::bind(static_cast&lt;void (*)(int)&gt;(print), 42);<br>    auto printString = std::bind(static_cast&lt;void (*)(const std::string&amp;)&gt;(print), &quot;Hello, world!&quot;);<br><br>    // Pass the bound objects to threads<br>    std::thread t1(printInt);<br>    std::thread t2(printString);<br><br>    t1.join();<br>    t2.join();<br><br>    return 0;<br>}</pre><h3>Why Direct Passing Without Disambiguation Fails</h3><p>If you attempt to pass the name of the overloaded function directly, the compiler will throw an error because it cannot deduce which version of the function you want to invoke.</p><pre>std::thread t(print, 42); // ERROR: Ambiguous call to overloaded function</pre><p>By using the methods above, you can make your intent explicit and successfully use overloaded functions with std::thread.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4853a9d9f46d" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>