<?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 İrem İkra Adlığ on Medium]]></title>
        <description><![CDATA[Stories by İrem İkra Adlığ on Medium]]></description>
        <link>https://medium.com/@iremikraadl?source=rss-85e6f05ad932------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*VbXUUD25B1UP5mnJ</url>
            <title>Stories by İrem İkra Adlığ on Medium</title>
            <link>https://medium.com/@iremikraadl?source=rss-85e6f05ad932------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 27 Nov 2026 23:24:20 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@iremikraadl/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[C++ CONCURRENCY 101]]></title>
            <link>https://medium.com/bosphorusiss/c-concurrency-101-2c17ffe8019e?source=rss-85e6f05ad932------2</link>
            <guid isPermaLink="false">https://medium.com/p/2c17ffe8019e</guid>
            <category><![CDATA[concurrency]]></category>
            <category><![CDATA[cpp]]></category>
            <category><![CDATA[engineering]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[multitasking]]></category>
            <dc:creator><![CDATA[İrem İkra Adlığ]]></dc:creator>
            <pubDate>Fri, 28 May 2021 06:10:31 GMT</pubDate>
            <atom:updated>2021-06-03T08:00:27.287Z</atom:updated>
            <content:encoded><![CDATA[<h3>What is concurrency?</h3><p>Scheduler arranges jobs, threads sequences or a computer’s operations into a non-deterministic way.</p><p>This is called <em>hardware concurrency</em>: multiple threads running on different cores in parallel, each of them taking care of a specific task of the program. <br>We can usestd::thread::hardware_concurrency() function to know how many tasks the hardware can run concurrently.</p><p>If the answer is more than one, this means we have multicore. Multicore refers to a computer or processor that has more than one logical CPU core, and that can physically execute multiple instructions at the same time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/962/1*SFz0Mx6e8NmLJF9Bh5oO3w.png" /></figure><p>If the answer is only one, we have only one core. Scheduler puts them in an order, and tasks work sequentially. It is like an illusion that we have multicore, but we do not. Processes share time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/714/1*OPF8mDUZls9s5JSabAKk7A.png" /></figure><h3>Why is synchronization needed?</h3><p>With multiple threads sharing the same address space and resources, a lot of operations become critical: multithreading requires synchronization primitives. This is why.</p><p>Imagine that we are working for a company, and it’s lunch time. Every employee gets in a line to get meal. If we do not synchronize, first employee will take its lunch, and the rest of the employees will wait in the line, until that person finishes his lunch. And process will be same for every single employee. Is it efficient?</p><p>Lets try to understand how <strong>task switching</strong> and <strong>time sharing</strong> work; again it’s lunch time. Everyone has a limited time to eat something and than the person whose time is expired should go back to the end of the line to wait for her/his turn. And this way everyone can eat something fairly and things are more efficient.</p><p>And now lets try to understand how multicore processors work. Lets assume that we have two line to get meal. So next turn comes faster. Scheduler arranges who goes to which line. Every employee is a thread in this example :)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WNysU7rpviazQHLo58sznA.jpeg" /><figcaption>:)</figcaption></figure><h3><strong>std::thread</strong></h3><p>std::thread is the thread class that represents a single thread in C++. Thread Class creates automatically a new thread and can take a callable as a parameter.</p><p><strong>A callable can be either of the three</strong><br>* A function pointer<br>* A function object<br>* A lambda expression</p><p><strong>USAGE:<br></strong>std::<strong>thread</strong> thread_object(callable)</p><pre>void func1()<br>{<br>    <a href="http://en.cppreference.com/w/cpp/io/cout">std::cout</a> &lt;&lt; &quot;Func1 is executing&quot; &lt;&lt; std::endl;<br>}<br>void func2(int n)<br>{<br>    <a href="http://en.cppreference.com/w/cpp/io/cout">std::cout</a> &lt;&lt; &quot;Func2 is executing&quot; &lt;&lt; std::endl;<br>}<br> <br>void func3(int&amp; n)<br>{<br>    <a href="http://en.cppreference.com/w/cpp/io/cout">std::cout</a> &lt;&lt; &quot;Func3 is executing&quot; &lt;&lt; std::endl;<br>}</pre><pre>int main()<br>{   int n = 0;  <br>    <a href="http://en.cppreference.com/w/cpp/thread/thread">std::</a><strong>thread</strong> t1(func1);<br>    <a href="http://en.cppreference.com/w/cpp/thread/thread">std::</a><strong>thread</strong> t2(func2, n); // pass by value<br>    <a href="http://en.cppreference.com/w/cpp/thread/thread">std::</a><strong>thread</strong> t3(func3, <a href="http://en.cppreference.com/w/cpp/utility/functional/ref">std::ref</a>(n)); // pass by reference<br>    <a href="http://en.cppreference.com/w/cpp/thread/thread">std::</a><strong>thread</strong> t4(std::move(t3)); // t4 is now running func3(). <br>                                   // t3 is no longer a thread<br>    std::<strong>thread</strong> t5([](params) { // Do Something };, params);<br>    <br>    t1.join();<br>    t2.join();<br>    t3.join();<br>    t4.join();<br>    t5.join();<br>    return 0;</pre><pre>}</pre><p><strong>Member Functions:<br>* </strong>joinable<br>* get_id<br>* native_handle<br>* hardware_concurrency<br>* join<br>* detach<br>* swap</p><p>The most used members of thread class are <strong>join()</strong> and <strong>detach()</strong>. If you want to wait for a thread to finish, call <strong>join().</strong> Join is a blocking function, so whenever you call join, caller process will wait for the end of the thread. By default a thread runs in joinable mode. Joinable thread will not release any resource even after the end of thread function, until we call join().</p><p>But some threads take too much time, if you don’t want to block any thread with calling join, call <strong>detach()</strong>. It will work on background independently. A Detached thread automatically releases it allocated resources on exit. No other thread needs to join it. After making a thread detached, you can not make the thread joinable again.</p><p>Use <strong>joinable()</strong> function if you need to check if thread is joinable. Do not join a thread if it is not joinable. <br>* Detached threads are not joinable. <br>* Uninitialized threads are not joinable.<br>* Joined threads are not joinable, because you already joined them.</p><pre>void foo()<br>{<br>    <a href="http://en.cppreference.com/w/cpp/thread/sleep_for">std::this_thread::sleep_for</a>(<a href="http://en.cppreference.com/w/cpp/chrono/duration">std::chrono::seconds</a>(1));<br>}<br> <br>int main()<br>{<br>    <a href="http://en.cppreference.com/w/cpp/thread/thread">std::thread</a> t;<br>    <a href="http://en.cppreference.com/w/cpp/io/cout">std::cout</a> &lt;&lt; &quot;before starting, joinable: &quot; &lt;&lt; <a href="http://en.cppreference.com/w/cpp/io/manip/boolalpha">std::boolalpha</a> &lt;&lt; t.joinable()<br>              &lt;&lt; &#39;<strong>\n</strong>&#39;;<br> <br>    t = <a href="http://en.cppreference.com/w/cpp/thread/thread">std::thread</a>(foo);<br>    <a href="http://en.cppreference.com/w/cpp/io/cout">std::cout</a> &lt;&lt; &quot;after starting, joinable: &quot; &lt;&lt; t.joinable() <br>              &lt;&lt; &#39;<strong>\n</strong>&#39;;<br> <br>    t.join();<br>    <a href="http://en.cppreference.com/w/cpp/io/cout">std::cout</a> &lt;&lt; &quot;after joining, joinable: &quot; &lt;&lt; t.joinable() <br>              &lt;&lt; &#39;<strong>\n</strong>&#39;;<br>}</pre><p>Output:</p><pre>before starting, joinable: false<br>after starting, joinable: true<br>after joining, joinable: false</pre><h3><strong>std::mutex(since c++11)</strong></h3><p>The <strong>mutex</strong> class is a synchronization primitive that can be used to protect shared data from being simultaneously accessed by multiple threads.<br>* A calling thread <em>owns</em> a mutex from the time that it successfully calls either <a href="https://en.cppreference.com/w/cpp/thread/mutex/lock">lock</a> or <a href="https://en.cppreference.com/w/cpp/thread/mutex/try_lock">try_lock</a> until it calls <a href="https://en.cppreference.com/w/cpp/thread/mutex/unlock">unlock</a>.<br>* Thread owns a mutex, all other threads will block (for calls to <a href="https://en.cppreference.com/w/cpp/thread/mutex/lock">lock</a>) or receive a false return value (for <a href="https://en.cppreference.com/w/cpp/thread/mutex/try_lock">try_lock</a>) if they attempt to claim ownership of the mutex.<br>* The behavior of a program is undefined if a mutex is destroyed while still owned by any threads, or a thread terminates while owning a mutex. std::mutex is neither copyable nor movable.</p><p><strong>USAGE:<br></strong>std::<strong>mutex</strong> mutex_name;</p><p><strong>Member Functions:<br>* </strong>lock<br>* try_lock<br>* unlock</p><pre>int x = 5;<br>std::mutex mtx;<br> <br>void function(int val)<br>{<br>   mtx.lock();   //after lock this thread, any other thread can&#39;t<br>                 //access this part until the thread unlocked<br>   x = val;<br>   <br>   mtx.unlock(); //releases the mutex<br>}<br> <br>int main() <br>{<br>    std::thread th1(function,10);<br>    std::thread th2(function,5);<br><br>    th1.join();<br>    th2.join();<br>    return 0;</pre><pre>}</pre><p>(std::mutex is usually not accessed directly. <a href="https://en.cppreference.com/w/cpp/thread/unique_lock">std::unique_lock</a>, <a href="https://en.cppreference.com/w/cpp/thread/lock_guard">std::lock_guard</a>, or <a href="https://en.cppreference.com/w/cpp/thread/scoped_lock">std::scoped_lock</a> (since C++17) manage locking in a more exception-safe manner. We will talk about these methods in the following sections.)</p><pre>int x = 5;<br>std::mutex mtx;<br> <br>void function(int val)<br>{<br>   mtx.lock();   //after lock this thread, any other thread can&#39;t<br>                 //access this part until the thread unlocked<br>   x = val;<br>   if(x == 10)   //if <strong>val </strong>is 10, function returns and mutex will<br>                 //never unlock, and program will stuck<br>                 //Because of that mutex is usually not accessed<br>                 //directly. Lets examine std::lock_guard<br>   {<br>      return;<br>   }   <br>   mtx.unlock(); //releases the mutex<br>}<br> <br>int main() <br>{<br>    std::thread th1(function,10);<br>    std::thread th2(function,5);<br><br>    th1.join();<br>    th2.join();<br>}</pre><h3><strong>std::lock_guard</strong></h3><p>The class lock_guard is a mutex wrapper that provides a convenient <a href="https://en.cppreference.com/w/cpp/language/raii">RAII-style</a> mechanism for owning a mutex for the duration of a scoped block.</p><p>When a lock_guard object is created, it attempts to take ownership of the mutex it is given. When control leaves the scope in which the lock_guard object was created, the lock_guard is destructed and the mutex is released.</p><p>The lock_guard class is non-copyable.</p><p>We are creating a local object here, that will lock the mutex automatically, and its destructor otomatically unlock the mutex.</p><p><strong>USAGE:<br></strong>std::<strong>mutex</strong> mutex_name;<br>std::<strong>lock_guard&lt;std::mutex&gt;</strong> guard_name(mutex_name);</p><pre>int x = 5;<br>std::mutex mtx;<br> <br>void function(int val)<br>{<br>  std::lock_guard&lt;std::mutex&gt; mutex(mtx); //mutex is a local object <br>  //and it is otomatically destruct at the end of the scope and its <br>  //destructor otomatically unlocked the mutex</pre><pre>  x = val;<br>   if(x == 10)   <br>   {<br>      return;<br>   }   <br>}<br> <br>int main() <br>{<br>    std::thread th1(function,10);<br>    std::thread th2(function,5);<br><br>    th1.join();<br>    th2.join();<br>}</pre><h4><strong>Wait for the next story, std::async and Task Based Concurrency..</strong></h4><p><strong>REFERENCES</strong></p><ul><li><a href="https://en.cppreference.com/w/cpp/thread/thread">std::thread</a></li><li><a href="https://en.cppreference.com/w/cpp/thread/mutex">std::mutex</a></li><li><a href="https://www.cplusplus.com/reference/mutex/mutex/">mutex - C++ Reference</a></li><li><a href="https://en.cppreference.com/w/cpp/thread/lock_guard">std::lock_guard</a></li><li><a href="https://thispointer.com/posix-detached-vs-joinable-threads-pthread_join-pthread_detach-examples/">POSIX : Detached vs Joinable threads | pthread_join() &amp; pthread_detach() examples</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2c17ffe8019e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/bosphorusiss/c-concurrency-101-2c17ffe8019e">C++ CONCURRENCY 101</a> was originally published in <a href="https://medium.com/bosphorusiss">BosphorusISS</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>