<?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 Hari Perev on Medium]]></title>
        <description><![CDATA[Stories by Hari Perev on Medium]]></description>
        <link>https://medium.com/@hatronix?source=rss-80017470a1ad------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*QXT7b81oJWTo_XM-ChrwZw.png</url>
            <title>Stories by Hari Perev on Medium</title>
            <link>https://medium.com/@hatronix?source=rss-80017470a1ad------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 16:51:28 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@hatronix/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[Mastering C++ Declarations: Arrays of Integers, Arrays of Pointers, and Pointers to Arrays of…]]></title>
            <link>https://medium.com/@hatronix/mastering-c-declarations-arrays-of-integers-arrays-of-pointers-and-pointers-to-arrays-of-1d4faf7d265d?source=rss-80017470a1ad------2</link>
            <guid isPermaLink="false">https://medium.com/p/1d4faf7d265d</guid>
            <category><![CDATA[pointers]]></category>
            <category><![CDATA[c-programming]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[memory-management]]></category>
            <category><![CDATA[c-plus-plus-language]]></category>
            <dc:creator><![CDATA[Hari Perev]]></dc:creator>
            <pubDate>Tue, 31 Oct 2023 02:59:31 GMT</pubDate>
            <atom:updated>2023-10-31T02:59:31.790Z</atom:updated>
            <content:encoded><![CDATA[<h3>Mastering C++ Declarations: Arrays of Integers, Arrays of Pointers, and Pointers to Arrays of Integers</h3><p>Arrays and pointers are fundamental concepts in C++ that allow you to efficiently manage and manipulate data. In this blog post, we’ll explore three important topics: an array of 5 integers, an array of 5 pointers, and a pointer to an array of 5 integers. By the end of this article, you’ll have a solid understanding of these concepts and how to use them in your C++ programming.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/794/1*yb2YcXMBRWECg885PZ0aZg.jpeg" /></figure><h3>Array of 5 Integers</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/530/1*Bj3e3M-x7SdanwXTVllHoA.gif" /><figcaption>Array of 5 Integers</figcaption></figure><p>In C++, an array is a collection of elements of the same data type. Let’s start by creating an array of 5 integers:</p><pre>int myIntArray[5] = {1, 2, 3, 4, 5};</pre><p>Here, we’ve declared an array named `myIntArray` containing five integer values. Arrays in C++ are zero-based, so you can access these elements using indices from 0 to 4. For example, to access the third element, you’d use `myIntArray[2]`.</p><pre>#include &lt;iostream&gt;<br><br>int main() {<br>    int myIntArray[5] = {1, 2, 3, 4, 5};<br><br>    for (int i = 0; i &lt; 5; i++) {<br>        std::cout &lt;&lt; &quot;Element &quot; &lt;&lt; i &lt;&lt; &quot; Memory Location: &quot; &lt;&lt; &amp;myIntArray[i] &lt;&lt; std::endl;<br>        std::cout &lt;&lt; &quot;Size of Variable: &quot; &lt;&lt; sizeof(myIntArray[i]) &lt;&lt; &quot; bytes&quot; &lt;&lt; std::endl;<br>        std::cout &lt;&lt; &quot;Value: &quot; &lt;&lt; myIntArray[i] &lt;&lt; std::endl;<br>        std::cout &lt;&lt; &quot;--------------------------&quot; &lt;&lt; std::endl;<br>    }<br><br>    return 0;<br>}<br><br>// Element 0 Memory Location: 0x7ffcf52b0200<br>// Size of Variable: 4 bytes<br>// Value: 1<br>// --------------------------<br>// Element 1 Memory Location: 0x7ffcf52b0204<br>// Size of Variable: 4 bytes<br>// Value: 2<br>// --------------------------<br>// Element 2 Memory Location: 0x7ffcf52b0208<br>// Size of Variable: 4 bytes<br>// Value: 3<br>// --------------------------<br>// Element 3 Memory Location: 0x7ffcf52b020c<br>// Size of Variable: 4 bytes<br>// Value: 4<br>// --------------------------<br>// Element 4 Memory Location: 0x7ffcf52b0210<br>// Size of Variable: 4 bytes<br>// Value: 5<br>// --------------------------</pre><p>In this example, we have an array of 5 integers (myIntArray). The code iterates through the array, printing the memory location of each element, the size of the variable, and the value of the variable.</p><h3>Array of 5 Pointers</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/530/1*lVauj7WePDKywBNmWbfSoQ.gif" /><figcaption>Array of 5 Pointers</figcaption></figure><p>Now, let’s explore an array of 5 pointers. Pointers in C++ are variables that store memory addresses. In this case, we’ll create an array of pointers to integers:</p><pre>int * myPointerArray[5];</pre><p>This declaration creates an array of 5 pointers to integers. You can use each element of the array to point to different integer variables. For example:</p><pre>int vara = 10, varb = 20, varc = 30, vard = 40, vare = 50;<br><br>myPointerArray[0] = &amp;vara;<br>myPointerArray[1] = &amp;varb;<br>myPointerArray[2] = &amp;varc;<br>myPointerArray[3] = &amp;vard;<br>myPointerArray[4] = &amp;vare;</pre><pre>#include &lt;iostream&gt;<br><br>int main() {<br>    int vara = 10, varb = 20, varc = 30, vard = 40, vare = 50;<br>    int* myPointerArray[5];<br><br>    myPointerArray[0] = &amp;vara;<br>    myPointerArray[1] = &amp;varb;<br>    myPointerArray[2] = &amp;varc;<br>    myPointerArray[3] = &amp;vard;<br>    myPointerArray[4] = &amp;vare;<br><br>    for (int i = 0; i &lt; 5; i++) {<br>        std::cout &lt;&lt; &quot;Pointer &quot; &lt;&lt; i &lt;&lt; &quot; Memory Location: &quot; &lt;&lt; myPointerArray[i] &lt;&lt; std::endl;<br>        std::cout &lt;&lt; &quot;Size of Variable Pointed to: &quot; &lt;&lt; sizeof(*myPointerArray[i]) &lt;&lt; &quot; bytes&quot; &lt;&lt; std::endl;<br>        std::cout &lt;&lt; &quot;Value: &quot; &lt;&lt; *myPointerArray[i] &lt;&lt; std::endl;<br>        std::cout &lt;&lt; &quot;--------------------------&quot; &lt;&lt; std::endl;<br>    }<br><br>    return 0;<br>}<br><br>// Pointer 0 Memory Location: 0x7ffdd17f4288<br>// Size of Variable Pointed to: 4 bytes<br>// Value: 10<br>// --------------------------<br>// Pointer 1 Memory Location: 0x7ffdd17f428c<br>// Size of Variable Pointed to: 4 bytes<br>// Value: 20<br>// --------------------------<br>// Pointer 2 Memory Location: 0x7ffdd17f4290<br>// Size of Variable Pointed to: 4 bytes<br>// Value: 30<br>// --------------------------<br>// Pointer 3 Memory Location: 0x7ffdd17f4294<br>// Size of Variable Pointed to: 4 bytes<br>// Value: 40<br>// --------------------------<br>// Pointer 4 Memory Location: 0x7ffdd17f4298<br>// Size of Variable Pointed to: 4 bytes<br>// Value: 50<br>// --------------------------</pre><p>In this example, we have five integer variables (vara, varb, varc, vard, vare), and we store their addresses in an array of pointers (myPointerArray). The code then iterates through this array, printing the memory location of each pointer, the size of the variable it points to, and the value of the variable.</p><h3>Pointer to an Array of 5 Integers</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/530/1*coysKuWW-S_AmvQ7aPKAXg.gif" /><figcaption>Pointer to an Array of 5 Integers</figcaption></figure><p>Now, let’s discuss a pointer to an array. This is a pointer that points to the first element of an array. To create a pointer to an array of 5 integers, you can do the following:</p><pre>int (*ptrToArray)[5];</pre><p>Here, `ptrToArray` is a pointer that can point to an array of 5 integers. You can initialize it like this:</p><pre>int myIntArray[5] = {1, 2, 3, 4, 5};<br>ptrToArray = &amp;myIntArray;</pre><p>Now, `ptrToArray` points to the array `myIntArray`. You can access the elements using the pointer just like you would with a regular array.</p><pre>#include &lt;iostream&gt;<br><br>int main() {<br>    int myIntArray[5] = {1, 2, 3, 4, 5};<br>    int (*ptrToArray)[5]; // Pointer to an array of 5 integers<br><br>    ptrToArray = &amp;myIntArray; // Point the pointer to the array<br><br>    // Accessing elements using the pointer (Method 1)<br>    for (int i = 0; i &lt; 5; i++) {<br>        std::cout &lt;&lt; &quot;Print Element Method 1 &quot; &lt;&lt; i &lt;&lt; &quot;: &quot; &lt;&lt; (*ptrToArray)[i] &lt;&lt; std::endl;<br>    }<br>    <br>    // Accessing elements using the pointer (Method 2)<br>    for (int i = 0; i &lt; 5; i++) {<br>        std::cout &lt;&lt; &quot;Print Element Method 2 &quot; &lt;&lt; i &lt;&lt; &quot;: &quot; &lt;&lt; *(*ptrToArray + i) &lt;&lt; std::endl;<br>    }<br><br>    return 0;<br>}<br><br>// Print Element Method 1 0: 1<br>// Print Element Method 1 1: 2<br>// Print Element Method 1 2: 3<br>// Print Element Method 1 3: 4<br>// Print Element Method 1 4: 5<br>// Print Element Method 2 0: 1<br>// Print Element Method 2 1: 2<br>// Print Element Method 2 2: 3<br>// Print Element Method 2 3: 4<br>// Print Element Method 2 4: 5</pre><p>In this example, we have an array of 5 integers named myIntArray, and a pointer to an array of 5 integers named ptrToArray. We then point the ptrToArray to the myIntArray. To access the elements of the array using the pointer, we use (*ptrToArray)[i] syntax, which allows us to treat the pointer as if it were a regular array. This loop iterates through the elements of the array and prints their values, demonstrating that you can access the elements using the pointer just like you would with a regular array.</p><h3>Conclusion</h3><p>Arrays and pointers are powerful tools in C++, and understanding how to work with them is essential for any C++ developer. In this blog post, we’ve explored an array of 5 integers, an array of 5 pointers, and a pointer to an array of 5 integers. These concepts are building blocks for more advanced data structures and algorithms, so mastering them will benefit you in your C++ programming journey.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1d4faf7d265d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Go WaitGroup: Wait for multiple goroutines to finish]]></title>
            <link>https://medium.com/@hatronix/go-waitgroup-wait-for-multiple-goroutines-to-finish-b092f3278393?source=rss-80017470a1ad------2</link>
            <guid isPermaLink="false">https://medium.com/p/b092f3278393</guid>
            <category><![CDATA[concurrency]]></category>
            <category><![CDATA[concurrent-programming]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[go]]></category>
            <dc:creator><![CDATA[Hari Perev]]></dc:creator>
            <pubDate>Mon, 30 Oct 2023 11:27:29 GMT</pubDate>
            <atom:updated>2023-10-30T11:27:29.387Z</atom:updated>
            <content:encoded><![CDATA[<p>The sync package provides a WaitGroup to wait for multiple goroutines to finish their execution. It ensures that the main program doesn’t exit before all goroutines have completed. You increment and decrement the WaitGroup counter to coordinate goroutines.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/806/1*wKvPHLH9MT4QzQK_tPYF5A.jpeg" /></figure><blockquote>Wait groups are a powerful tool for concurrency management in Go. They enable you to pause and synchronize program execution until a collection of goroutines finishes their tasks.</blockquote><h3>WaitGroup process</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/529/1*P7W2254yrtaEJVQ7F1KZ5A.jpeg" /><figcaption>Go WaitGroup process</figcaption></figure><p><strong>Add()</strong> is used to add the number of goroutines that need to be waited upon.</p><p><strong>Done() </strong>is called by each goroutine when it finishes its work, decrementing the internal counter of the wait group.</p><p><strong>Wait()</strong> is used to block the execution of the goroutine until all the goroutines have called Done().</p><p>By incrementing the wait group counter with Add(), each goroutine signals that it needs to be waited upon. <br>When a goroutine finishes its work, it calls Done(), reducing the wait group counter. The main goroutine or another goroutine can then call Wait() to block until the wait group counter reaches zero.</p><h3>WaitGroup Creation</h3><p>Before starting a goroutine, increment the WaitGroup counter using the Add method. This tells the WaitGroup how many goroutines you expect to wait for. You typically increment the counter before launching each goroutine.</p><h3>Wait for Goroutines to Finish</h3><p>To wait for all the spawned goroutines to complete, you call the Wait method on the WaitGroup. This method blocks until the counter is decremented to zero, indicating that all goroutines have finished their work.</p><pre>package main<br><br>import (<br>    &quot;fmt&quot;<br>    &quot;sync&quot;<br>)<br><br>func main() {<br>    var wg sync.WaitGroup<br><br>    for i := 1; i &lt;= 5; i++ {<br>        wg.Add(1)<br>        go func(id int) {<br>            defer wg.Done()<br>            fmt.Printf(&quot;Goroutine %d started\n&quot;, id)<br>        }(i)<br>    }<br><br>    wg.Wait() // Wait for all goroutines to finish<br><br>    fmt.Println(&quot;All goroutines have completed.&quot;)<br>}<br><br>// Goroutine 5 started<br>// Goroutine 1 started<br>// Goroutine 2 started<br>// Goroutine 3 started<br>// Goroutine 4 started<br>// All goroutines have completed.</pre><p>In this example, you’ll observe that the order in which the goroutines start is not predictable. However, you can be sure that they will all complete before the “All goroutines have completed” message is printed.</p><h3>WaitGroup Sequence</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/265/1*2o0-fG2Wue-hxqKgyr3T4g.jpeg" /><figcaption>WaitGroup Sequence</figcaption></figure><p>As mentioned earlier, the order in which the goroutines complete can vary, depending on factors like the scheduler’s decisions, CPU availability, and the nature of the work performed by each goroutine. If you need to enforce a specific sequence of execution or coordinate the order in which goroutines complete, you may need to use additional synchronization mechanisms like channels or mutexes.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b092f3278393" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Go Mutex: Providing synchronization in concurrent Go programs]]></title>
            <link>https://medium.com/@hatronix/go-mutex-providing-synchronization-in-concurrent-go-programs-75aa6dc67b92?source=rss-80017470a1ad------2</link>
            <guid isPermaLink="false">https://medium.com/p/75aa6dc67b92</guid>
            <category><![CDATA[go]]></category>
            <category><![CDATA[mutex]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[concurrency]]></category>
            <category><![CDATA[defer]]></category>
            <dc:creator><![CDATA[Hari Perev]]></dc:creator>
            <pubDate>Mon, 30 Oct 2023 10:59:56 GMT</pubDate>
            <atom:updated>2023-10-30T11:01:22.142Z</atom:updated>
            <content:encoded><![CDATA[<p>Concurrency in programming requires safeguarding data and preventing clashes between processes. Go’s sync.Mutex simplifies this by controlling access to shared resources. In this post, we’ll explore mutexes in Go, learn how to use them, and see how they help prevent conflicts.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/806/1*EMCsOOWIqP8AHSrPoyqdFA.jpeg" /></figure><blockquote>A mutex, which stands for mutual exclusion, helps keep shared stuff safe from being messed up by lots of goroutines at once. It’s like a key that only one goroutine can have at a time to use a special part of the code. Without it, things could get mixed up and go wrong. Mutexes stop that from happening. They’re part of Go’s standard sync package.</blockquote><h3>What is Mutex in Go?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/265/1*qK2xwNGvJgkAHYMcxet8qw.jpeg" /><figcaption>Mutex Diagram</figcaption></figure><p>A mutex in Go is a synchronization primitive provided by the sync package. It is used to protect shared resources from simultaneous access by multiple goroutines. A mutex allows only one goroutine at a time to access a critical section of code, ensuring that concurrent access is controlled and preventing data races.</p><h3>Where is Mutex Used in Go?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/398/1*tsJrMVMMtW_6ysYUq0JhmA.jpeg" /><figcaption>Goroutines Accessing the same shared resource</figcaption></figure><p>Mutexes are used in Go wherever shared resources need to be accessed and modified by multiple goroutines concurrently. They are commonly used in the following scenarios:<br>• Protecting shared data structures, such as maps or slices, from concurrent read and write operations.<br>• Synchronizing access to shared files or I/O resources.<br>• Coordinating access to global variables or shared state in a concurrent program.</p><h3>When is Mutex Used in Go?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/265/1*AoB_R7VzaiAuYObKgmLwqA.jpeg" /><figcaption>The result must be three, however, because of the race condition, the result is two.</figcaption></figure><p>Mutexes are used when there is a need to coordinate and synchronize access to shared resources to prevent race conditions. <br>Race conditions occur when multiple goroutines concurrently access and modify shared data, leading to unpredictable and erroneous behaviour.<br>Mutexes are used to ensure data integrity by allowing one goroutine at a time to perform operations on shared resources in a controlled and exclusive manner.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/265/1*0cFvJLWU4RSWqNDBexoHog.jpeg" /><figcaption>race condition resolved</figcaption></figure><h3>How is Mutex Used in Go?</h3><p>In Go, you typically use a mutex in the following manner:<br>Create a mutex variable using sync.Mutex. To protect a critical section of code, call Lock() on the mutex before accessing the shared resource. This prevents other goroutines from entering the same critical section simultaneously. After you’re done with the critical section, call Unlock() on the mutex to release the lock, allowing other goroutines to access the critical section.</p><p>Here’s a simplified example of how a mutex is used in Go:</p><pre>package main<br><br>import (<br> &quot;fmt&quot;<br> &quot;sync&quot;<br>)<br><br>func main() {<br> var mu sync.Mutex<br> sharedData := 0<br><br> // Goroutine 1<br> go func() {<br>  mu.Lock()<br>  sharedData++<br>  mu.Unlock()<br> }()<br><br> // Goroutine 2<br> go func() {<br>  mu.Lock()<br>  sharedData--<br>  mu.Unlock()<br> }()<br><br> // Wait for the goroutines to complete<br> mu.Lock()<br> fmt.Println(&quot;Final Value:&quot;, sharedData)<br> mu.Unlock()<br>}</pre><p>In this example, we create a mutex named mu, and two goroutines safely modify the sharedData variable by acquiring and releasing the lock using mu.Lock() and mu.Unlock(). The mutex ensures that the shared data is accessed in a synchronized manner.</p><h3>RWMutex — Safely Allow Multiple Readers</h3><p>RWMutex is an abbreviation for “Reader-Writer Mutex” in Go, and it is a synchronization primitive provided by the sync package. It’s used to manage access to shared resources in a way that allows for multiple readers but only one writer at a time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/265/1*n8l7DWb2sPrvvn_n-PoDTg.jpeg" /><figcaption>Reader-Writer Mutex</figcaption></figure><p>Using sync.RWMutex over sync.Mutex is advantageous when you have scenarios where multiple goroutines frequently read shared data but write operations are less frequent. sync.RWMutex allows multiple goroutines to acquire a read lock simultaneously, which is more efficient for read-heavy workloads compared to using a sync.Mutex, which allows only one goroutine at a time for any read or write operation.</p><pre>package main<br><br>import (<br> &quot;fmt&quot;<br> &quot;sync&quot;<br> &quot;time&quot;<br>)<br><br>func main() {<br> var data int<br> var rwMutex sync.RWMutex<br><br> // Multiple readers<br> for i := 0; i &lt; 3; i++ {<br>  go func() {<br>   rwMutex.RLock()<br>   defer rwMutex.RUnlock()<br>   fmt.Println(&quot;Read data:&quot;, data)<br>  }()<br> }<br><br> // Single writer<br> go func() {<br>  rwMutex.Lock()<br>  defer rwMutex.Unlock()<br>  data = 42<br>  fmt.Println(&quot;Write data:&quot;, data)<br> }()<br><br> time.Sleep(time.Second)<br>}<br><br>// Read data: 0<br>// Read data: 0<br>// Read data: 0<br>// Write data: 42</pre><h3>Conclusion</h3><p>Mutexes are essential for concurrent programming, ensuring synchronization and preventing race conditions. In Go, the sync.Mutex and sync.RWMutex types empowers developers to safeguard shared resources and manage access to critical code sections.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=75aa6dc67b92" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Go Go: lockless techniques for managing state and synchronization]]></title>
            <link>https://medium.com/@hatronix/go-go-lockless-techniques-for-managing-state-and-synchronization-5398370c379b?source=rss-80017470a1ad------2</link>
            <guid isPermaLink="false">https://medium.com/p/5398370c379b</guid>
            <category><![CDATA[locks]]></category>
            <category><![CDATA[golang-concurrency]]></category>
            <category><![CDATA[concurrency]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[go]]></category>
            <dc:creator><![CDATA[Hari Perev]]></dc:creator>
            <pubDate>Mon, 30 Oct 2023 10:39:35 GMT</pubDate>
            <atom:updated>2023-10-30T10:41:20.672Z</atom:updated>
            <content:encoded><![CDATA[<h3>Atomic Operations in Go: Lockless techniques for managing state and synchronization</h3><p>Concurrency is a fundamental aspect of modern software development, and writing concurrent programs in Go is a relatively painless task thanks to its robust concurrency support.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/806/1*C0nXyLLGjls8Bspkx6BO1Q.png" /></figure><blockquote>Go provides built-in support for atomic operations, which play a crucial role in synchronizing concurrent programs. In this blog post, we will explore the concept of atomic operations in Go, understand why they are essential, and how to use them effectively.</blockquote><h3>What are atomic operations in Go ?</h3><p>In Go, atomic operations are operations that are designed to be executed without interruption and without interference from other concurrent operations. They are used to ensure that certain operations on shared variables are performed atomically, meaning they are executed as a single, indivisible unit, and they are not subject to interference or data races from other goroutines or threads.</p><p>Go provides a package named sync/atomic that includes a set of functions for performing atomic operations on primitive data types, such as integers and pointers. Some of the commonly used atomic operations in Go include:</p><h4>Load</h4><p>The atomic.Load* functions are used to atomically read the value of a variable. For example, atomic.LoadInt32 is used to atomically load the value of an int32 variable.</p><h4>Store</h4><p>The atomic.Store* functions are used to atomically set the value of a variable. For example, atomic.StoreInt32 is used to atomically set the value of an int32 variable.</p><h4>Add and Subtract</h4><p>The atomic.Add* and atomic.Sub* functions are used to atomically increment or decrement the value of a variable.</p><h4>Compare and Swap (CAS)</h4><p>The atomic.CompareAndSwap* functions are used to atomically compare the current value of a variable with an expected value and, if they match, set the variable to a new value. This is commonly used for implementing lock-free data structures and algorithms.</p><h4>Swap</h4><p>The atomic.Swap* functions are used to atomically swap the value of a variable with a new value.</p><p>These atomic operations are valuable when working with shared variables in a concurrent environment to prevent data races and ensure that operations on the variables are performed safely and consistently. They help in building concurrent data structures, synchronization primitives, and managing shared resources in a thread-safe manner.</p><h3>Do I need a mutex to use this operations ?</h3><p>In Go, the sync/atomic package provides atomic operations that can be used without a mutex to perform atomic updates on shared variables. The key advantage of using atomic operations is that they are typically more efficient than using traditional mutexes, especially for simple operations on primitive data types like integers and pointers.</p><p>You do not need a mutex when using atomic operations because these operations are designed to be thread-safe and perform atomic updates without the need for explicit locking and unlocking of a mutex. Atomic operations operate on the hardware level, ensuring that the operations are performed atomically, preventing data races and avoiding the need for traditional locking mechanisms.</p><p>However, it’s important to note that atomic operations have their limitations. They are best suited for simple, low-level updates on primitive data types. If you need to perform more complex operations that involve multiple variables or require more intricate synchronization, you may still need to use mutexes or other synchronization primitives.</p><p>In summary, while atomic operations can be used without a mutex for simple, atomic updates on shared variables, the choice between atomic operations and mutexes depends on the specific requirements and complexity of the concurrent task at hand. It’s essential to choose the right synchronization mechanism based on the specific needs of your concurrent code.</p><pre>package main<br><br>import (<br> &quot;fmt&quot;<br> &quot;sync/atomic&quot;<br> &quot;time&quot;<br>)<br><br>func main() {<br> var counter int32<br><br> // Create a goroutine to increment the counter.<br> go func() {<br>  for i := 0; i &lt; 5; i++ {<br>   atomic.AddInt32(&amp;counter, 1)<br>   fmt.Printf(&quot;Incremented: %d\n&quot;, atomic.LoadInt32(&amp;counter))<br>   time.Sleep(time.Millisecond)<br>  }<br> }()<br><br> // Create a goroutine to decrement the counter.<br> go func() {<br>  for i := 0; i &lt; 5; i++ {<br>   atomic.AddInt32(&amp;counter, -1)<br>   fmt.Printf(&quot;Decremented: %d\n&quot;, atomic.LoadInt32(&amp;counter))<br>   time.Sleep(time.Millisecond)<br>  }<br> }()<br><br> // Wait for the goroutines to finish.<br> time.Sleep(2 * time.Second)<br><br> fmt.Printf(&quot;Final Value: %d\n&quot;, atomic.LoadInt32(&amp;counter))<br>}<br><br>// Decremented: -1<br>// Incremented: 0<br>// Incremented: 1<br>// Decremented: 0<br>// Decremented: -1<br>// Incremented: 0<br>// Incremented: 1<br>// Decremented: 0<br>// Decremented: -1<br>// Incremented: 0<br>// Final Value: 0</pre><p>We have a shared counter variable of type int32.<br>Two goroutines are created, one to increment and another to decrement the counter. We use atomic.AddInt32 to atomically add or subtract from the counter. We use atomic.LoadInt32 to safely load the value of the counter for printing. The program waits for the goroutines to finish using time.Sleep. The use of atomic operations ensures that the counter is updated safely without the need for a mutex. You should see that the counter is correctly incremented and decremented in a race-free manner.<br>The sequence of events demonstrates that the operations are correctly interleaved, resulting in a final value of 0 for the counter.<br>This output confirms that the atomic operations are working as intended to ensure the safety of shared data without requiring a mutex for synchronization.</p><h3>Conclusion</h3><p>Atomic operations are a crucial tool for ensuring the correctness and performance of concurrent programs in Go. By allowing for safe manipulation of shared memory, they enable developers to write efficient and reliable concurrent code. However, it’s essential to use them judiciously and understand the potential trade-offs when dealing with concurrency in your Go applications. With a solid understanding of atomic operations and proper use, you can build robust and responsive concurrent programs in Go.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5398370c379b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Structs in C: An In-Depth Guide]]></title>
            <link>https://medium.com/@hatronix/mastering-structs-in-c-an-in-depth-guide-4a524af06fd4?source=rss-80017470a1ad------2</link>
            <guid isPermaLink="false">https://medium.com/p/4a524af06fd4</guid>
            <category><![CDATA[c-programming]]></category>
            <category><![CDATA[structure-in-c]]></category>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[low-level-programming]]></category>
            <dc:creator><![CDATA[Hari Perev]]></dc:creator>
            <pubDate>Mon, 30 Oct 2023 08:55:28 GMT</pubDate>
            <atom:updated>2023-10-30T08:55:28.634Z</atom:updated>
            <content:encoded><![CDATA[<p>In the world of programming, data is king. Managing data efficiently is essential, and C, one of the most powerful and versatile programming languages, provides a remarkable tool for this purpose: structures.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/794/1*_hVSUI3421mh06rWkCAFGQ.jpeg" /></figure><blockquote>In C, structures, often referred to as structs, are a fundamental concept. They allow you to define custom data types by grouping related variables together under a single name. In this blog post, we will explore structs in C, covering their understanding, importance, and providing a practical example.</blockquote><h3>Understanding Structs</h3><p>A struct in C is a composite data type that lets you bundle together variables of different data types. This grouping allows you to organize and manipulate related data more easily. Think of a struct as a container for multiple variables, each with its own data type, enclosed within a single structure. The syntax for defining a struct is as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/530/1*9JWMe-cbmE6g02PX6armqA.gif" /><figcaption>Structs in C</figcaption></figure><pre>struct YourStructName {<br>    // Members or fields go here<br>    char member1;<br>    int member2;<br>    double member3;<br>    // ...more members<br>};</pre><p>In the example above, we’ve defined a struct named YourStructName with three members: including a character (char), an integer (int), and a double (double) .</p><h3>Structure Definitions</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/265/1*dWyamgRfu6w6oZhPd5x-CA.jpeg" /><figcaption>Struct definitions in C</figcaption></figure><h4><strong>Anonymous Structure:</strong></h4><pre>struct {<br>    int a;<br>    char b;<br>};</pre><p>This is an anonymous structure because it is not given a name. <br>In C and C++, you can define structures without naming them. <br>In this case, you are defining a structure with two members: an integer ‘a’ and a character ‘b’.</p><p>Calling an anonymous structure is not straightforward because you cannot create variables of this type directly. It’s not recommended to use anonymous structures in practice.</p><h4><strong>Named Structure:</strong></h4><pre>struct name_top {<br>    int a;<br>    char b;<br>};</pre><p>This is a named structure called “name_top.” You are defining a structure with the name “name_top” that has two members: an integer ‘a’ and a character ‘b’.</p><p>To use this structure, you can declare variables of this type like this:</p><pre>struct name_top myStruct;</pre><p>Here, “myStruct” is a variable of type “struct name_top,” and you can access its members as `myStruct.a` and `myStruct.b`.</p><h4><strong>Named Structure with Variable Declaration:</strong></h4><pre>struct {<br>    int a;<br>    char b;<br>} name_bot;</pre><p>In this example, you are defining a structure similar to the anonymous structure, but you are also declaring a variable of this structure type named “name_bot.”</p><p>To use this structure and its associated variable, you can declare variables of this type like this:</p><pre>name_bot myStruct;</pre><p>Here, “myStruct” is a variable of the anonymous structure type with the name “name_bot,” and you can access its members as `myStruct.a` and `myStruct.b`.</p><h4><strong>Anonymous vs Named Structure</strong></h4><p>It’s important to note that anonymous structures are not commonly used because they cannot be easily reused, and their members are not directly accessible in other parts of the code. Named structures, on the other hand, provide a clear and reusable way to define complex data structures in C and C++.</p><h4><strong>Structure Definition and Variable Declaration in a single statement:</strong></h4><pre>struct name_top {<br>    int a;<br>    char b;<br>} name_bot;</pre><ol><li>Structure Definition:<br>You are defining a structure named “name_top” with two members: an integer ‘a’ and a character ‘b’. This structure can be used to create variables of type “struct name_top.”</li><li>Variable Declaration:<br>You are also declaring a variable named “name_bot” of type “struct name_top.” This means you’ve created a variable of the “name_top” structure type and named it “name_bot.”</li></ol><p>To use this structure and variable, you can access the members like this:</p><pre>name_bot myStruct; // Declare a variable of type &quot;name_top&quot; named &quot;myStruct&quot;<br>myStruct.a = 42;   // Assign a value to the &#39;a&#39; member<br>myStruct.b = &#39;X&#39;;  // Assign a value to the &#39;b&#39; member</pre><p>In this example, “myStruct” is an instance of the “name_top” structure, and you can access and manipulate its members using the dot notation, as shown above.</p><h4>Typedef structures in C</h4><p>In C, you can use the typedef keyword to create type aliases for structures. This is helpful for making your code more readable and concise, as well as for defining custom data types.</p><pre>typedef struct my_name {<br>    int a;<br>    char b;<br>} my_alias_t;</pre><p>You are defining a structure named my_name with two members, an integer a and a character b. Additionally, you are using the typedef keyword to create a new type alias named my_alias_t for this structure.</p><p>This typedef statement allows you to use my_alias_t as a shorthand for declaring variables of the my_name structure type. For example, you can now declare a variable like this:</p><pre>my_alias_t myVar;</pre><p>The use of typedef is particularly useful for enhancing code readability and making your code more maintainable. It provides a more descriptive name (my_alias_t) for the type, which can make your code easier to understand, especially when working with complex data structures.</p><h4>Packed vs Unpacked Structures</h4><p>In C and C++, structures are typically laid out in memory with memory alignment and padding to ensure efficient memory access and alignment of data. However, you can control how structures are laid out using the packed attribute or pragma to create packed structures.</p><h4>Unpacked Structures:</h4><p>Unpacked structures are the default in C and C++. They follow the standard memory alignment rules for the target architecture. The compiler may insert padding bytes between members to ensure that each member is correctly aligned in memory for efficient access. For example, on many systems, integers are aligned on 4-byte boundaries.</p><pre>#include &lt;stdio.h&gt;<br><br>struct UnpackedStruct {<br>    char a;    // 1 byte<br>    int b;     // 4 bytes (assuming a typical 4-byte int)<br>    char c;    // 1 byte<br>};<br><br>int main() {<br>    printf(&quot;Size of UnpackedStruct: %lu\n&quot;, sizeof(struct UnpackedStruct));<br>    return 0;<br>}<br><br>// Size of UnpackedStruct: 12</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/530/1*E7reeiZ6yhtKNxzQ5t9H3Q.jpeg" /><figcaption>Unpacked Struct in C</figcaption></figure><p>The padding in this case is introduced to align the int member b on a 4-byte boundary because accessing an int at an unaligned memory location can lead to performance issues on some architectures. <br>The compiler’s decision to add padding is based on the specific platform’s memory alignment requirements and the data types used. This is why the size of the structure is 12 bytes on this particular system. The padding ensures that each member is properly aligned in memory for efficient access, at the expense of a larger memory footprint.</p><h4>Packed Structures:</h4><p>The provided code below defines a structure named PackedStruct with the __attribute__((packed)) directive in a GCC compiler environment. This directive tells the compiler to create a packed structure, which eliminates padding between structure members to minimize memory usage.</p><pre>#include &lt;stdio.h&gt;<br><br>struct PackedStruct  {<br>    char a;<br>    int b;<br>    char c;<br>}__attribute__((packed));<br><br>int main() {<br>    printf(&quot;Size of char: %lu\n&quot;, sizeof(char));<br>    printf(&quot;Size of int: %lu\n&quot;, sizeof(int));<br>    printf(&quot;Size of PackedStruct: %lu\n&quot;, sizeof(struct PackedStruct));<br>    return 0;<br>}<br><br>// Size of char: 1<br>// Size of int: 4<br>// Size of PackedStruct: 6</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/530/1*3IqrlqzQ7e28xuNnunrRzg.jpeg" /><figcaption>Packed Struct in C</figcaption></figure><p>This demonstrates that using the __attribute__((packed)) directive in GCC creates a more memory-efficient structure with no padding, which can be useful when minimizing memory usage is crucial. However, be cautious when using packed structures, as they may lead to unaligned memory access and potential performance issues on certain platforms.</p><h4>Conclusion</h4><p>Structs make your code more organized, enhance data abstraction, and offer a clean way to represent related data in a structured manner.</p><p>In conclusion, structs are an essential feature in C, and understanding their usage is fundamental to mastering the language. They empower you to create organized, efficient, and reusable data structures, enabling you to work with complex data in a structured and modular fashion.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4a524af06fd4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Function Pointers in C: Unleashing the Power of Dynamic Dispatch]]></title>
            <link>https://medium.com/@hatronix/function-pointers-in-c-unleashing-the-power-of-dynamic-dispatch-29672ffcf502?source=rss-80017470a1ad------2</link>
            <guid isPermaLink="false">https://medium.com/p/29672ffcf502</guid>
            <category><![CDATA[c-programming]]></category>
            <category><![CDATA[function-pointer]]></category>
            <category><![CDATA[callback-function]]></category>
            <category><![CDATA[cplusplus]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Hari Perev]]></dc:creator>
            <pubDate>Sun, 29 Oct 2023 21:08:35 GMT</pubDate>
            <atom:updated>2023-11-05T14:27:44.877Z</atom:updated>
            <content:encoded><![CDATA[<p>Function pointers in C are pointers that can store the address of a function. They allow you to treat functions as data, enabling you to call functions indirectly, pass functions as arguments to other functions, and store functions in data structures like arrays or tables.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/794/1*LgCGQaj4qaFu1Vhjb-H3fQ.jpeg" /></figure><h4>Syntax and usage of function pointers in C</h4><p><strong>Declaration:</strong> Function pointers are declared like any other pointer, but with the appropriate function signature. The signature specifies the return type and the types of the function’s parameters.</p><pre>int (*fnPtr)(int, int);</pre><p><strong>Initialization:</strong> Function pointers are typically initialized by assigning them the address of a function. You can use the function’s name without parentheses to get the address of the function.</p><pre>fnPtr = &amp;someFunction; // or simply fnPtr = someFunction;</pre><p><strong>Calling Functions through Pointers:</strong> You can call the function indirectly using the function pointer. This can be done with or without dereferencing the pointer.</p><pre>int result = fnPtr(5, 3); // Calling the function via pointer</pre><h4>Use Cases</h4><p><strong>Callback Functions:</strong> Function pointers are commonly used for implementing callback mechanisms. For example, in event-driven programming or handling interrupts, you can register a function that gets called when an event occurs.</p><p><strong>Dynamic Dispatch:</strong> In scenarios where you have multiple functions with similar interfaces but different implementations (polymorphism), you c use function pointers to switch between these functions at runtime.</p><p><strong>Function Tables:</strong> Function pointers can be stored in arrays or other data structures to create function tables, where you can select and call functions based on an index or condition.</p><p><strong>Plug-ins and Extensions:</strong> In applications that support plug-ins or extensions, function pointers are used to call dynamically loaded functions.</p><h4><strong>Case Study — Building a Function Table</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/265/1*h5lm9M8QgnoHfuhceu2_2w.gif" /><figcaption>Function Pointer calling other functions</figcaption></figure><pre>#include &lt;stdio.h&gt;<br><br>// Function prototypes for home automation actions<br>typedef void (*ActionFunction)(void);<br><br>// Function to turn on lights<br>void turnOnLights() {<br>    printf(&quot;Lights turned on.\n&quot;);<br>}<br><br>// Function to adjust the thermostat<br>void adjustThermostat() {<br>    printf(&quot;Thermostat adjusted.\n&quot;);<br>}<br><br>// Function to play music<br>void playMusic() {<br>    printf(&quot;Music playing.\n&quot;);<br>}<br><br>int main() {<br>    // Function table for home automation actions<br>    ActionFunction actionTable[] = {<br>        turnOnLights,<br>        adjustThermostat,<br>        playMusic<br>    };<br><br>    int userChoice;<br><br>    // Simulate user input (1 for lights, 2 for thermostat, 3 for music)<br>    printf(&quot;Enter your choice (1 for lights, 2 for thermostat, 3 for music): &quot;);<br>    scanf(&quot;%d&quot;, &amp;userChoice);<br><br>    // Check if the user input is within the function table&#39;s bounds<br>    if (userChoice &gt;= 1 &amp;&amp; userChoice &lt;= 3) {<br>        // Call the selected function using function pointer<br>        ActionFunction selectedAction = actionTable[userChoice - 1];<br>        selectedAction();<br>    } else {<br>        printf(&quot;Invalid choice.\n&quot;);<br>    }<br><br>    return 0;<br>}</pre><p>In this example, we’ve defined three actions: turnOnLights(), adjustThermostat(), and playMusic(). We’ve created a function pointer type ActionFunction that represents functions taking no arguments and returning void. We’ve also created a function table actionTable that holds these functions.The program simulates user input, and based on the user’s choice, it selects the corresponding function from the function table and calls it using the function pointer. This approach provides a clean and efficient way to manage different actions in an embedded system, making it easy to add or modify actions as needed. This case study demonstrates how function pointers can be a valuable tool in embedded systems for implementing dynamic dispatch and making the code more modular and maintainable.</p><h4>Caveats</h4><p>When working with function pointers, make sure the function signature (return type and parameter types) matches the declaration of the function pointer.</p><p>Function pointers are not compatible with function pointers of different signatures.</p><p>Dereferencing a null or uninitialized function pointer can lead to undefined behavior.</p><p>Debugging can be challenging when function pointers are involved, as the function called is determined at runtime.</p><h4>Conclusion</h4><p>Function pointers are a powerful feature in C that allow for flexibility and dynamic behaviour in your programs, but they require careful handling to ensure type safety and correct execution.</p><h4>Now lets get serious with a help of <a href="https://cdecl.org/">https://cdecl.org/</a></h4><h4>Returning an Integer</h4><pre>int (*p)(void);</pre><p>Declare p as pointer to function (void) returning int.</p><h4>Returning an Array of Integers</h4><pre>int (*(*p)(void))[100];</pre><p>Declare p as pointer to function (void) returning pointer to array 100 of int.</p><pre>int (*(*p)(const void *))[3]</pre><p>Declare p as pointer to function (pointer to const void) returning pointer to array 3 of int.</p><h4>Returning an Pointer to Integer</h4><pre>int* (*p)(void);</pre><p>Declares p as pointer to function (void) returning pointer to int.</p><h4>Returning an Array of Pointers to Integers</h4><pre>int* (*(*p)(void))[100];</pre><p>Declares p as pointer to function (void) returning pointer to array 100 of pointer to int.</p><h4>Returning an Array of Function Pointers (an array of size 100, each pointing to a function taking no arguments and returning an integer)</h4><pre>int (*p[100])(void);</pre><p>Declares an array p of 100 function pointers, where each function takes (void) and returns an integer.</p><h4>Returning an Array of Function Pointers (an array of size 100, each pointing to a function taking no arguments and returning an array of pointers to integer)</h4><pre>int* (*(*p[100])(void))[100];</pre><p>Declares an array p of 100 function pointers, where each function points to a function that takes (void) arguments and returns an array of pointers to integers.</p><h4>Returning an pointer to function that has int as argument and returns char *</h4><pre>char* (*(*p)(void))(int);</pre><p>Declare p as pointer to function (void) returning pointer to function (int) returning pointer to char.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=29672ffcf502" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Go Channels: Pipes that connect 
concurrent goroutines]]></title>
            <link>https://medium.com/@hatronix/go-channels-pipes-that-connect-concurrent-goroutines-7b2bb3368179?source=rss-80017470a1ad------2</link>
            <guid isPermaLink="false">https://medium.com/p/7b2bb3368179</guid>
            <category><![CDATA[asynchronous]]></category>
            <category><![CDATA[go]]></category>
            <category><![CDATA[goroutines]]></category>
            <category><![CDATA[concurrency]]></category>
            <category><![CDATA[golang]]></category>
            <dc:creator><![CDATA[Hari Perev]]></dc:creator>
            <pubDate>Wed, 25 Oct 2023 21:58:28 GMT</pubDate>
            <atom:updated>2023-10-25T22:00:21.590Z</atom:updated>
            <content:encoded><![CDATA[<h3>Go Channels: Pipes that connect <br>concurrent goroutines</h3><p>Go is a programming language known for its excellent support for concurrency. At the heart of this concurrency model are channels.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/806/1*o65jZUT5Ot-AlLTE1s_dOA.png" /></figure><blockquote>Channels provide a safe and efficient means for goroutines to communicate and synchronize their activities. In this article, we’ll explore the fundamentals of channels, including unbuffered and buffered channels, as well as channel direction, which includes unidirectional and bidirectional channels.</blockquote><h4>Channel syntax:</h4><p>The syntax for sending and receiving values from channels is straightforward and uses the &lt;- operator. The direction of the arrow (&lt;-) indicates whether you are sending to or receiving from a channel. <br>Here are the basic syntax forms for sending and receiving:</p><p><strong>Sending a Value into a Channel: ch &lt;- value</strong><br>To send a value into a channel, you use the &lt;- operator with the channel variable on the left and the value on the right.</p><p><strong>Receiving a Value from a Channel: receivedValue := &lt;-ch</strong><br>To receive a value from a channel, you also use the &lt;- operator, but this time with the channel variable on the right and the variable that will store the received value on the left.</p><h4>Unbuffered Channels:</h4><p>Unbuffered channels, also known as <strong>synchronous channels</strong>, are the simplest type of channel in Go. They allow data to be passed between goroutines, ensuring that the sender and receiver are synchronized. When a value is sent on an unbuffered channel, the sender blocks until the receiver is ready to receive it, and vice versa.</p><p>Consider this example:</p><pre>ch := make(chan int)<br>go func() {<br>    value := 42<br>    ch &lt;- value // Send a value into the unbuffered channel<br>}()<br>receivedValue := &lt;-ch // Receive the value from the channel (blocks until data is available)</pre><p>Unbuffered channels are often used when precise synchronization is required between goroutines.</p><h4>Buffered Channels:</h4><p>Buffered channels, on the other hand, allow multiple values to be stored in the channel before the receiver is ready to receive them. This buffer size defines the capacity of the channel. Buffered channels are <strong>asynchronous</strong> and can be used for scenarios where strict synchronization is not necessary, such as sending data to a pool of worker goroutines.</p><p>Here’s an example of a buffered channel:</p><pre>ch := make(chan int, 3) // Create a buffered channel with a capacity of 3<br>go func() {<br>    for i := 1; i &lt;= 3; i++ {<br>        ch &lt;- i // Send values into the buffered channel (won&#39;t block until the buffer is full)<br>    }<br>}()</pre><h4>Unidirectional Channels:</h4><p>Go allows you to create unidirectional channels, which restrict certain channel operations to enforce communication patterns. There are two types: send-only channels (<strong>chan&lt;-</strong>) and receive-only channels (<strong>&lt;-chan</strong>). Send-only channels can only send data, while receive-only channels can only receive data.</p><pre>func sendMessages(sendCh chan&lt;- string) {<br>    // Send messages into the sendCh channel<br>}<br><br>func receiveMessages(recvCh &lt;-chan string) {<br>    // Receive messages from the recvCh channel<br>}</pre><p>Unidirectional channels help prevent unintended misuse of channels and make the code more explicit.</p><h4>Channel direction syntax:</h4><p><strong>&lt;-chan (Receive-Only Channel):</strong><br>This notation is used to declare a channel that can only be used for receiving data. It restricts the channel to only allow receiving operations (e.g., reading from the channel). A receive-only channel is also referred to as a read-only channel. For example: ch &lt;-chan int declares a channel that can only be read from.</p><p><strong>chan&lt;- (Send-Only Channel):</strong><br>This notation is used to declare a channel that can only be used for sending data. It restricts the channel to only allow sending operations (e.g., writing to the channel). A send-only channel is also referred to as a write-only channel. For example: ch chan&lt;- int declares a channel that can only be written to.</p><h4>Bidirectional Channels:</h4><p>Bidirectional channels are the most common type and allow both sending and receiving operations. They provide flexibility for communication between goroutines and are created without specifying a direction. Goroutines can both send and receive data using these channels.</p><pre>ch := make(chan int)<br>go func() {<br>    ch &lt;- 42 // Send a value into the bidirectional channel<br>}()<br>receivedValue := &lt;-ch // Receive a value from the bidirectional channel</pre><p>Bidirectional channels are the workhorses of Go’s concurrency model and are used in most concurrent programs.</p><h4>Channel Blocking:</h4><p>Blocking refers to the behaviour of a goroutine when it’s waiting for a specific operation to complete. In the context of channels, blocking occurs when a goroutine attempts to send or receive data through a channel, but the operation cannot proceed until another goroutine is ready to receive or send data. Blocking is a fundamental mechanism in Go for synchronization and ensuring that goroutines operate in a coordinated manner.</p><p>For example, when you perform a receive operation &lt;-ch on an empty channel, the receiving goroutine will block until there is data available to be received. Similarly, when you send a value ch &lt;- value on a full channel, the sending goroutine will block until there is space available in the channel for the data.</p><h4>Deadlocks:</h4><p>A deadlock is a situation where two or more goroutines are stuck, waiting for each other to release a resource, such as a channel, so that they can proceed. In the context of channels, a deadlock can occur when there’s a circular dependency in your goroutines’ interactions with channels, causing them to wait indefinitely for each other. For example, if two goroutines are both trying to send data to each other on unbuffered channels, they can each become blocked because they are waiting for the other to receive data first, creating a deadlock situation.</p><p>Here’s an example of a potential deadlock:</p><pre>package main<br><br>import &quot;fmt&quot;<br><br>func main() {<br>    ch1 := make(chan int)<br>    ch2 := make(chan int)<br><br>    go func() {<br>        value := &lt;-ch1 // Receive from ch1<br>        ch2 &lt;- value   // Send to ch2<br>    }()<br><br>    go func() {<br>        value := &lt;-ch2 // Receive from ch2<br>        ch1 &lt;- value   // Send to ch1<br>    }()<br><br>    // These two goroutines will become deadlocked.<br>    // Each is waiting for the other to send data.<br>    select {}<br>}<br><br>// fatal error: all goroutines are asleep - deadlock!</pre><p>In this example, the two goroutines are stuck waiting for the other to send data, creating a deadlock scenario.</p><p>To avoid deadlocks, you need to carefully design your concurrent code to ensure that there are no circular dependencies in your channel interactions. Proper synchronization techniques like using select and channels with buffer capacities can help you prevent deadlocks and manage blocking effectively in your Go programs.</p><h4>Closing Channels:</h4><p>Closing channels in is a signalling mechanism to indicate that no more values will be sent on the channel. It’s a way to inform the receiving goroutines that they should stop waiting for new data. When a channel is closed, it can still be used for receiving any remaining values in the buffer, but any further send operations will result in a panic.</p><p>Here’s how to close a channel and use it with an example:</p><pre>package main<br><br>import (<br> &quot;fmt&quot;<br> &quot;time&quot;<br>)<br><br>func main() {<br> ch := make(chan int)<br><br> // Sender goroutine<br> go func() {<br>  defer close(ch) // Close the channel when done sending<br>  for i := 1; i &lt;= 5; i++ {<br>   ch &lt;- i // Send values into the channel<br>  }<br> }()<br><br> // Receiver goroutine<br> go func() {<br>  for value := range ch {<br>   fmt.Println(&quot;Received:&quot;, value)<br>  }<br> }()<br><br> // Wait for the goroutines to finish<br> time.Sleep(2 * time.Second)<br>}</pre><p>In this example:<br>We create a channel ch using make(chan int).<br>In the sender goroutine, we use defer close(ch) to ensure the channel is closed when the sender is done sending data. After sending all the values (1 to 5), the channel is closed. In the receiver goroutine, we use a for loop with range to continuously receive values from the channel. The loop will automatically terminate when the channel is closed. The time.Sleep(2 * time.Second) statement at the end is used to keep the program running to allow the goroutines to complete their work. This is a common way to prevent the main function from exiting prematurely. By closing the channel, we signal to the receiver that there will be no more values sent, and it can safely exit its loop.</p><h4>Channel synchronization</h4><p>Channel synchronization is a mechanism in Go that allows goroutines to coordinate and communicate with each other using channels. It ensures that certain operations or tasks are completed in a specific order or that multiple goroutines can work together cooperatively.<br>Here’s an example of channel synchronization where two goroutines take turns printing “Ping” and “Pong” to the console:</p><pre>package main<br><br>import (<br> &quot;fmt&quot;<br> &quot;sync&quot;<br>)<br><br>func main() {<br> var wg sync.WaitGroup<br> pingCh := make(chan bool)<br> pongCh := make(chan bool)<br><br> wg.Add(1) // One WaitGroup for the first goroutine<br><br> go func() {<br>  defer wg.Done()<br>  for i := 0; i &lt; 5; i++ {<br>   fmt.Println(&quot;Ping&quot;)<br>   pongCh &lt;- true<br>   &lt;-pingCh<br>  }<br> }()<br><br> go func() {<br>  wg.Add(1) // One WaitGroup for the second goroutine<br>  defer wg.Done()<br>  for i := 0; i &lt; 5; i++ {<br>   &lt;-pongCh<br>   fmt.Println(&quot;Pong&quot;)<br>   pingCh &lt;- true<br>  }<br> }()<br><br> wg.Wait() // Wait for the first goroutine to finish<br> close(pingCh)<br> close(pongCh)<br>}<br><br>//Ping<br>//Pong<br>//Ping<br>//Pong<br>//Ping<br>//Pong<br>//Ping<br>//Pong<br>//Ping<br>// Pong</pre><p>In this example: <br>We use a sync.WaitGroup to wait for the first goroutine to finish. The wg.Add(1) and wg.Done() calls ensure that we wait for the first goroutine to complete its tasks. We remove the initial pingCh &lt;- true, which was causing the initial deadlock. The second goroutine also uses a sync.WaitGroup to ensure it completes its tasks before the program exits. We close both pingCh and pongCh to signal that no more values will be sent, which helps gracefully end the goroutines. With these changes, you should see alternating “Ping” and “Pong” messages printed to the console, and the program will exit without any deadlock.</p><h4>Conclusion:</h4><p>Channels are a fundamental concept in Go’s concurrency model, and mastering them is essential for building efficient and robust concurrent applications. Understanding the basics of unbuffered and buffered channels, as well as channel direction (unidirectional and bidirectional), provides a solid foundation for creating concurrent programs that are both safe and performant. Whether you’re building a simple parallel program or a complex distributed system, Go’s channel model is a powerful tool in your toolkit.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7b2bb3368179" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Goroutine: Lightweight thread managed by the Go runtime]]></title>
            <link>https://medium.com/@hatronix/goroutine-lightweight-thread-managed-by-the-go-runtime-d9df7db5c88d?source=rss-80017470a1ad------2</link>
            <guid isPermaLink="false">https://medium.com/p/d9df7db5c88d</guid>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[goroutines]]></category>
            <category><![CDATA[go]]></category>
            <dc:creator><![CDATA[Hari Perev]]></dc:creator>
            <pubDate>Wed, 25 Oct 2023 01:38:58 GMT</pubDate>
            <atom:updated>2023-10-25T01:38:58.782Z</atom:updated>
            <content:encoded><![CDATA[<p>A goroutine is a lightweight, independently executing concurrent thread of control in the Go programming language. Goroutines are a fundamental building block of concurrent and parallel programming in Go. They allow you to execute functions concurrently, making it easy to write concurrent programs in a readable and manageable way.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/806/1*i8vHgrO4WXxk7_UoLl3gCg.jpeg" /></figure><h4>What is achieved by using a Goroutine?</h4><p><strong>Concurrency:</strong> They enable concurrent execution of tasks, making it easier to write efficient and responsive programs that can take advantage of multi-core processors.</p><p><strong>Simplicity:</strong> Goroutines make concurrent programming more accessible by providing an easy-to-use, lightweight concurrency model. They are much simpler to work with than traditional threads or processes.</p><p><strong>Efficiency:</strong> Goroutines are lightweight in terms of memory and resources, so you can create many of them without significantly impacting the performance of your program.</p><p><strong>Asynchronous Operations:</strong> Goroutines are suitable for handling I/O-bound and asynchronous tasks without blocking the main thread, allowing your program to remain responsive.</p><h4>When is a Goroutine Used?</h4><p>Goroutines are used in Go when you want to achieve concurrent execution of tasks. They are particularly useful in scenarios where you have tasks that can be performed independently and simultaneously, such as:</p><ul><li>Handling multiple network connections concurrently.<br>• Performing parallel processing of data, like in map-reduce tasks.<br>• Running background tasks, such as monitoring, logging, or periodic cleanup.<br>• Handling concurrent I/O operations without blocking.<br>• Any situation where you want to achieve concurrency and take advantage of multi-core processors.</li></ul><h4>Goroutine code workflow</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/529/1*sGT3Wc_XeJeOt2AP3Nb0Bw.jpeg" /><figcaption>Goroutine code workflow</figcaption></figure><pre>package main<br><br>import (<br> &quot;fmt&quot;<br> &quot;sync&quot;<br>)<br><br>func main() {<br> fmt.Println(&quot;Start&quot;)<br><br> var wg sync.WaitGroup<br><br> // Create two goroutines, func1 and func2<br> wg.Add(2)<br> go func1(&amp;wg)<br> go func2(&amp;wg)<br><br> // Wait for both goroutines to complete<br> wg.Wait()<br><br> fmt.Println(&quot;End&quot;)<br>}<br><br>func func1(wg *sync.WaitGroup) {<br> defer wg.Done()<br> fmt.Println(&quot;func 1&quot;)<br>}<br><br>func func2(wg *sync.WaitGroup) {<br> defer wg.Done()<br> fmt.Println(&quot;func 2&quot;)<br>}<br><br>// Start<br>// func 1<br>// func 2<br>// End</pre><h4>Goroutine running workflow</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/265/1*suLkMnnOeKDLhnLy3mfORQ.jpeg" /><figcaption>Goroutine running workflow</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/265/1*AuLqsaUeddP4nY8tSovzEQ.gif" /><figcaption>Goroutine transition diagram</figcaption></figure><p>When a goroutine is created with the go keyword, it’s added to a queue of goroutines to be scheduled. The Go scheduler selects an idle logical processor (P) from the pool and assigns the next goroutine to run on that P.<br>The P’s associated thread (M) executes the goroutine’s code. When the goroutine is preempted (e.g., due to a system call or a blocking operation), the scheduler can switch to another goroutine on the same P. If a goroutine voluntarily yields control (e.g., with runtime.Gosched()), the scheduler can switch to another goroutine. The Go scheduler manages the coordination of goroutines, and when a goroutine completes, it may be terminated.</p><h4>Goroutines lifecycle</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/265/1*PJ0zWgC0a4aQgG8fmoQOjw.gif" /><figcaption>Goroutines lifecycle</figcaption></figure><p><strong>Created: </strong>When you create a Goroutine using the go keyword, it transitions to the “created” state. In this state, the Goroutine is ready to run but has not started executing yet. The Go runtime scheduler will eventually start it when CPU time becomes available.</p><p><strong>Running:</strong> Once the scheduler starts executing a Goroutine, it enters the “running” state. In this state, the Goroutine’s code is actively being executed on a processor (CPU core). The Goroutine may yield control to the scheduler, allowing other Goroutines to run.</p><p><strong>Blocked:</strong> A Goroutine can transition to the “blocked” state for various reasons, such as: Waiting for input on a channel (channel &lt;- data) when the channel is empty. Acquiring a lock or mutex that is currently held by another Goroutine. Making a system call that blocks (e.g., reading from a file or waiting for network data). Waiting for a specific event or condition to be met. In the “blocked” state, the Goroutine is temporarily paused and gives up its CPU time until the blocking condition is resolved.</p><p><strong>Exit:</strong> The “exit” state occurs when a Goroutine completes its execution.<br>This can happen when the Goroutine reaches the end of its function, returns a value, or encounters an error. In the “exit” state, the Goroutine is terminated, and its resources are released. It no longer participates in the concurrent execution of the program.</p><h4>M:N scheduler</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/265/1*1-M33MseRdYfd43dOq1Ivw.jpeg" /><figcaption>M:N scheduler</figcaption></figure><p>In Go, the M:N scheduler is a key component of the runtime system that manages goroutines and their execution on multiple OS threads. <br>The M:N scheduler model is designed to efficiently manage a large number of goroutines on a smaller number of OS threads, providing concurrency and parallelism while minimizing the overhead of thread creation and management.</p><h4>Here’s how the M:N scheduler works in Go:</h4><p><strong>Goroutines (M):</strong> Goroutines are lightweight threads of execution in Go. They are managed by the Go runtime and can be spawned easily. Goroutines are multiplexed onto a smaller number of OS threads.<br><strong>OS Threads (N):</strong> Go runtime utilizes a smaller number of OS threads, typically equal to the number of CPU cores available. These OS threads are responsible for executing the goroutines. The OS threads are managed by the Go runtime and are often referred to as “M” because they are closely associated with the goroutines they run.</p><h4>How is single kernel thread multiplexing goroutines?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/529/1*sKkGr6ABoRmZ1faRrTyigA.jpeg" /><figcaption>single kernel thread multiplexing goroutines</figcaption></figure><p>In Go, a key feature of its concurrency model is the ability for a single kernel thread to support multiple goroutines. This approach is part of what makes Go’s goroutines so efficient and lightweight compared to traditional threads in many other programming languages.</p><p><strong>Kernel Threads:</strong> In a typical operating system, a kernel thread is a unit of execution that the OS scheduler manages. Each kernel thread is associated with a specific OS-level stack and other resources.</p><p><strong>Goroutines:</strong> Goroutines, as implemented in Go, are lightweight threads of execution. They are not one-to-one mapped to kernel threads. Instead, multiple goroutines can run on a single kernel thread. This is made possible by the Go runtime’s scheduler, which multiplexes goroutines onto a smaller number of OS threads.</p><p><strong>Concurrency:</strong> When multiple goroutines run on a single kernel thread, they take turns executing. The Go scheduler manages the switching between goroutines, ensuring that they get a fair share of CPU time. This scheduling happens cooperatively, which means that goroutines voluntarily yield control, such as during I/O operations or when they call runtime.Gosched().</p><p><strong>Efficiency:</strong> This design allows Go to create and manage a large number of goroutines without the overhead of creating and managing an equivalent number of OS threads. In many other programming languages, creating and managing threads is relatively expensive in terms of both memory and CPU resources.</p><p><strong>System Calls:</strong> When a goroutine makes a system call that would typically block a kernel thread, the Go runtime can migrate the goroutine to another available kernel thread. This migration ensures that the system call doesn’t block the entire OS thread and allows other goroutines to continue running.</p><p>The ability to support multiple goroutines on a single kernel thread is a fundamental feature of Go’s concurrency model. It allows Go to efficiently handle large numbers of concurrent tasks while minimizing the overhead of thread creation and management. It’s one of the reasons Go is particularly well-suited for concurrent and parallel programming.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d9df7db5c88d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Fine-Grained Control with runtime.LockOSThread() in Go]]></title>
            <link>https://medium.com/@hatronix/fine-grained-control-with-runtime-lockosthread-in-go-2254642eddac?source=rss-80017470a1ad------2</link>
            <guid isPermaLink="false">https://medium.com/p/2254642eddac</guid>
            <category><![CDATA[goroutines]]></category>
            <category><![CDATA[go-scheduler]]></category>
            <category><![CDATA[go-programming]]></category>
            <category><![CDATA[concurrency]]></category>
            <category><![CDATA[parallelism]]></category>
            <dc:creator><![CDATA[Hari Perev]]></dc:creator>
            <pubDate>Wed, 25 Oct 2023 01:01:02 GMT</pubDate>
            <atom:updated>2023-10-25T19:10:16.387Z</atom:updated>
            <content:encoded><![CDATA[<p>Go’s Goroutines are the backbone of concurrent programming, allowing you to run tasks concurrently with ease. While they are incredibly powerful, there are times when you need to exert precise control over the underlying operating system thread (OSThread) for tasks like thread affinity or system calls. This is where runtime.LockOSThread() comes into play. In this blog post, we&#39;ll explore the capabilities of runtime.LockOSThread() and how it can help you manage Goroutines with precision.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/806/1*k4YulWrqjkgS2fR2rcNrYQ.png" /></figure><h4>Unpacking runtime.LockOSThread():</h4><p>runtime.LockOSThread() is a function provided by Go&#39;s runtime package. It is used to lock the calling Goroutine to its current operating system thread, ensuring that the Goroutine remains associated with that thread during its execution.</p><h4>Why is it Important?</h4><ol><li><strong>Thread Affinity:</strong> In some cases, you may want to ensure that a particular Goroutine always runs on a specific OS thread. This is important for tasks like accessing platform-specific resources or libraries.</li><li><strong>System Calls:</strong> When dealing with system calls that must be made on a dedicated thread, runtime.LockOSThread() allows you to pin a Goroutine to a thread for these calls.</li><li><strong>Resource Isolation:</strong> By isolating a Goroutine to its own OS thread, you can prevent thread interference and simplify resource management for that Goroutine.</li><li><strong>Fine-Grained Control:</strong> runtime.LockOSThread() provides fine-grained control over Goroutine execution, enabling you to tailor your application for specific scenarios.</li></ol><h4>Example:</h4><p>Let’s explore an example that demonstrates how runtime.LockOSThread() can be used for thread affinity:</p><pre>package main<br><br>import (<br> &quot;fmt&quot;<br> &quot;runtime&quot;<br> &quot;sync&quot;<br>)<br><br>func main() {<br> runtime.GOMAXPROCS(2) // Set GOMAXPROCS to utilize two CPU cores<br><br> var wg sync.WaitGroup<br><br> // Start multiple Goroutines<br> for i := 1; i &lt;= 5; i++ {<br>  wg.Add(1)<br>  go worker(i, &amp;wg)<br> }<br><br> // Wait for all Goroutines to finish<br> wg.Wait()<br>}<br><br>func worker(id int, wg *sync.WaitGroup) {<br> defer wg.Done() // Notify that this Goroutine has completed<br><br> fmt.Printf(&quot;Goroutine %d is working...\n&quot;, id)<br><br> // Simulate some work<br><br> if id%2 == 0 {<br>  runtime.LockOSThread() // Lock this Goroutine to the current OS thread<br>  defer runtime.UnlockOSThread()<br> }<br><br> for i := 0; i &lt; 5; i++ {<br>  fmt.Printf(&quot;Goroutine %d is processing task %d\n&quot;, id, i)<br> }<br>}<br><br>// Goroutine 5 is working...<br>// Goroutine 1 is working...<br>// Goroutine 5 is processing task 0<br>// Goroutine 5 is processing task 1<br>// Goroutine 5 is processing task 2<br>// Goroutine 5 is processing task 3<br>// Goroutine 5 is processing task 4<br>// Goroutine 2 is working...<br>// Goroutine 2 is processing task 0<br>// Goroutine 2 is processing task 1<br>// Goroutine 2 is processing task 2<br>// Goroutine 2 is processing task 3<br>// Goroutine 2 is processing task 4<br>// Goroutine 1 is processing task 0<br>// Goroutine 1 is processing task 1<br>// Goroutine 1 is processing task 2<br>// Goroutine 1 is processing task 3<br>// Goroutine 1 is processing task 4<br>// Goroutine 4 is working...<br>// Goroutine 4 is processing task 0<br>// Goroutine 4 is processing task 1<br>// Goroutine 4 is processing task 2<br>// Goroutine 4 is processing task 3<br>// Goroutine 4 is processing task 4<br>// Goroutine 3 is working...<br>// Goroutine 3 is processing task 0<br>// Goroutine 3 is processing task 1<br>// Goroutine 3 is processing task 2<br>// Goroutine 3 is processing task 3<br>// Goroutine 3 is processing task 4</pre><p>In this example, we create multiple worker Goroutines, and every other Goroutine (with an even ID) is locked to the current OS thread using runtime.LockOSThread() for thread affinity.</p><h4>Conclusion:</h4><p>runtime.LockOSThread() is a powerful tool in your Go concurrency toolkit, offering fine-grained control over Goroutine execution. Whether you need thread affinity for certain tasks, dedicated threads for system calls, or resource isolation, this function provides the means to tailor your application to specific requirements. By understanding and utilizing runtime.LockOSThread(), you can build high-performance, efficient, and tightly controlled Go applications.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2254642eddac" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Graceful Goroutine Exits with runtime.Goexit() in Go]]></title>
            <link>https://medium.com/@hatronix/graceful-goroutine-exits-with-runtime-goexit-in-go-ee3dc2d4cd57?source=rss-80017470a1ad------2</link>
            <guid isPermaLink="false">https://medium.com/p/ee3dc2d4cd57</guid>
            <category><![CDATA[goroutines]]></category>
            <category><![CDATA[parallelism]]></category>
            <category><![CDATA[go-scheduler]]></category>
            <category><![CDATA[go-programming]]></category>
            <category><![CDATA[concurrency]]></category>
            <dc:creator><![CDATA[Hari Perev]]></dc:creator>
            <pubDate>Wed, 25 Oct 2023 00:50:34 GMT</pubDate>
            <atom:updated>2023-10-25T19:15:44.590Z</atom:updated>
            <content:encoded><![CDATA[<p>Concurrent programming in Go often involves managing multiple Goroutines, each with its own tasks and responsibilities. While starting Goroutines is a common practice, it’s equally important to know how to exit them gracefully. In this blog post, we’ll explore the power of runtime.Goexit() and how it can be used to manage Goroutine exits in your Go applications.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/806/1*QDuYqoDU8Cw74EQyefZv1Q.png" /></figure><h4>Understanding runtime.Goexit():</h4><p>runtime.Goexit() is a function provided by Go&#39;s runtime package. It is used to exit the currently running Goroutine gracefully. Unlike os.Exit(), which exits the entire program, runtime.Goexit() is designed specifically for Goroutine-level exits.</p><h4>Why is it Important?</h4><ol><li>Clean Exits: runtime.Goexit() allows Goroutines to exit cleanly and return control to the parent Goroutine or main function. This is essential for managing resource cleanup and preventing memory leaks.</li><li>Concurrency Control: In highly concurrent applications, managing Goroutine lifecycles is crucial. runtime.Goexit() gives you control over when and how a Goroutine should exit, ensuring efficient concurrency management.</li><li>Resource Reclamation: When a Goroutine exits, it can release resources, such as channels and memory, back to the system. Proper resource reclamation is vital for long-running applications.</li><li>Hierarchical Control: Goroutines are often organized hierarchically, and runtime.Goexit() supports this structure by allowing Goroutines to exit while preserving the parent-child relationships.</li></ol><h4>Example:</h4><p>Let’s dive into an example to understand how runtime.Goexit() can be used to exit Goroutines gracefully:</p><pre>package main<br><br>import (<br> &quot;fmt&quot;<br> &quot;runtime&quot;<br> &quot;sync&quot;<br>)<br><br>func main() {<br> var wg sync.WaitGroup<br><br> // Start multiple Goroutines<br> for i := 1; i &lt;= 5; i++ {<br>  wg.Add(1)<br>  go worker(i, &amp;wg)<br> }<br><br> // Wait for all Goroutines to finish<br> wg.Wait()<br><br> fmt.Println(&quot;All Goroutines have completed.&quot;)<br>}<br><br>func worker(id int, wg *sync.WaitGroup) {<br> defer wg.Done() // Notify that this Goroutine has completed<br><br> fmt.Printf(&quot;Goroutine %d is working...\n&quot;, id)<br><br> // Simulate some work<br> for i := 0; i &lt; 5; i++ {<br>  fmt.Printf(&quot;Goroutine %d is processing task %d\n&quot;, id, i)<br> }<br><br> // Exit the Goroutine gracefully<br> runtime.Goexit()<br>}<br><br>// Goroutine 5 is working...<br>// Goroutine 5 is processing task 0<br>// Goroutine 5 is processing task 1<br>// Goroutine 5 is processing task 2<br>// Goroutine 5 is processing task 3<br>// Goroutine 4 is working...<br>// Goroutine 2 is working...<br>// Goroutine 2 is processing task 0<br>// Goroutine 2 is processing task 1<br>// Goroutine 2 is processing task 2<br>// Goroutine 2 is processing task 3<br>// Goroutine 2 is processing task 4<br>// Goroutine 3 is working...<br>// Goroutine 3 is processing task 0<br>// Goroutine 3 is processing task 1<br>// Goroutine 3 is processing task 2<br>// Goroutine 3 is processing task 3<br>// Goroutine 3 is processing task 4<br>// Goroutine 4 is processing task 0<br>// Goroutine 4 is processing task 1<br>// Goroutine 4 is processing task 2<br>// Goroutine 4 is processing task 3<br>// Goroutine 4 is processing task 4<br>// Goroutine 5 is processing task 4<br>// Goroutine 1 is working...<br>// Goroutine 1 is processing task 0<br>// Goroutine 1 is processing task 1<br>// Goroutine 1 is processing task 2<br>// Goroutine 1 is processing task 3<br>// Goroutine 1 is processing task 4<br>// All Goroutines have completed.</pre><p>In this example, we create multiple worker Goroutines and use runtime.Goexit() to exit each Goroutine after its work is complete. The sync.WaitGroup is used to wait for all Goroutines to finish before proceeding.</p><h4>Conclusion</h4><p>runtime.Goexit() is a valuable tool for managing Goroutine lifecycles in Go. It enables clean and graceful exits, efficient resource reclamation, and hierarchical control of Goroutines. Whether you&#39;re building a web server, a concurrent data processing pipeline, or any application with multiple Goroutines, runtime.Goexit() empowers you to create well-managed and efficient Goroutine exits, contributing to the robustness and stability of your Go programs.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ee3dc2d4cd57" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>