<?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 Suyog Kokaje on Medium]]></title>
        <description><![CDATA[Stories by Suyog Kokaje on Medium]]></description>
        <link>https://medium.com/@suyogkokaje6?source=rss-a5d8e005730------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*c6mo77LOJnCg_fK-jSA5Mg.jpeg</url>
            <title>Stories by Suyog Kokaje on Medium</title>
            <link>https://medium.com/@suyogkokaje6?source=rss-a5d8e005730------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 18:11:10 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@suyogkokaje6/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[The Weight of Waiting : An Anatomy of Hope and Disappointment]]></title>
            <link>https://medium.com/@suyogkokaje6/the-weight-of-waiting-an-anatomy-of-hope-and-disappointment-101c6152c33f?source=rss-a5d8e005730------2</link>
            <guid isPermaLink="false">https://medium.com/p/101c6152c33f</guid>
            <category><![CDATA[self-awareness]]></category>
            <category><![CDATA[psychology]]></category>
            <category><![CDATA[personal-growth]]></category>
            <category><![CDATA[life-lessons]]></category>
            <category><![CDATA[mental-health]]></category>
            <dc:creator><![CDATA[Suyog Kokaje]]></dc:creator>
            <pubDate>Fri, 24 Jul 2026 02:50:18 GMT</pubDate>
            <atom:updated>2026-07-24T02:56:11.898Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zr2sZTmu53YhcknMq8AkDg.png" /></figure><p>Waiting is rarely just the passive passage of time. It is an active emotional investment. Aquiet, tense contract we sign with the future, fueled by hope, expectation, and yearning. But when that contract breaks, it leaves behind a wreckage of hard questions about time, fairness, and the cost of caring.</p><p>Here is a complete exploration of this train of thought, broken down into its core emotional and philosophical layers.</p><h3>1. The Anatomy of Waiting: Investment vs. Outcome</h3><p>At its core, <strong>waiting is the bridge between a present reality and a desired future</strong>.</p><p>When we wait for a specific person or outcome, we aren’t just sitting still; we are projecting our mental and emotional energy forward.</p><ul><li><strong>If we get what we waited for:</strong> The time spent feels validated. We view the period of waiting as a test of patience, a period of devotion, or “time well spent.” The emotional return on investment matches the cost.</li><li><strong>If we don’t get what we wanted:</strong> The narrative completely flips. We retroactively label the entire waiting period as “wasted time.”</li></ul><blockquote><strong><em>Example:</em></strong><em> Consider someone who spends three years in a long-distance relationship, holding out hope that their partner will eventually move to their city. If the partner moves, those three years are remembered as a period of romantic resilience. If the partner breaks up with them instead, those same three years are suddenly viewed as “stolen time” or a fruitless sacrifice.</em></blockquote><h3>2. The Illusion of Fairness and the Selective Blind Spot</h3><p>Why does it feel so unfair when waiting ends in disappointment?</p><p>It feels unfair because <strong>hope creates a psychological bias</strong>. When we want something deeply, we tend to focus exclusively on the best-case scenario. We operate on the implicit belief that because our yearning is pure and our patience is long, the universe owes us a positive outcome.</p><p>We rarely pause at the beginning of the wait to ask: <em>“What if this doesn’t work out?”</em> Or if that thought does cross our minds, we willfully ignore it, reassuring ourselves with phrases like <em>“Everything happens for a reason”</em> or <em>“It will all fall into place eventually.”</em></p><p>In reality, outcomes are governed by free will, external circumstances, and probability not by how deeply we care or how long we’ve been standing in line. When the negative outcome hits, the shock isn’t just from losing the desired result; it’s from the sudden collapse of the hopeful story we built in our heads.</p><h3>3. The Hefty Price of Yearning: Does Disappointment Make Time a “Waste”?</h3><p>Is time spent waiting really wasted if things don’t go our way?</p><p>It depends on how we define value. If value is determined <strong>only by the final result</strong>, then yes, it feels like a total waste. You spent emotional currency, put other aspects of life on hold, and walked away empty-handed. You paid a hefty price; grief, disappointment, heart-wrenching loss for a destination you never reached.</p><p>However, if value includes <strong>who you became while waiting</strong>, the answer changes:</p><ul><li>You learned the limits of your endurance.</li><li>You discovered the capacity of your heart to hold onto hope.</li><li>You learned what you truly value enough to wait for in the first place.</li></ul><p>The grief of not getting what you want is real, but the time itself wasn’t erased it was simply lived under a different set of expectations.</p><h3>4. To Stop, to Quit, or to Keep Going: Courage vs. Self-Preservation</h3><p>When faced with the brutal possibility of the “dark side” of waiting, a crucial conflict arises: <strong>If we stop waiting because the potential pain is too high, does that make us cowards?</strong></p><p><strong>No.</strong> Recognizing that an investment is no longer serving you isn’t cowardice; it is self-preservation.</p><ul><li><strong>The Right to Yearn:</strong> We all have a natural, human right to desire love, connection, and success.</li><li><strong>The Reality of the Price:</strong> Unfortunately, life doesn’t offer a risk-free version of longing. Love, hope, and vulnerability always carry a tax: the possibility of heartbreak. You cannot open your heart to the potential of a high reward without simultaneously exposing it to high risk.</li></ul><p>Stopping or letting go isn’t quitting out of fear, it is choosing to stop paying interest on a debt that may never be repaid.</p><h3>Summary: Reframing the Equation</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Kowwc8cMl-sSzL7JPO2kbw.png" /></figure><p>Waiting will always feel unfair when it ends in loss, because human beings are wired to expect reciprocity for our pain. But acknowledging the risk of the dark side doesn’t mean we shouldn’t ever wait; it simply means we must choose carefully <em>what</em> and <em>who</em> is worth the gamble.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=101c6152c33f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Freeze Time, Master Life: A Smarter Way to Grow]]></title>
            <link>https://medium.com/@suyogkokaje6/freeze-time-master-life-a-smarter-way-to-grow-a21f4f1f5ba4?source=rss-a5d8e005730------2</link>
            <guid isPermaLink="false">https://medium.com/p/a21f4f1f5ba4</guid>
            <dc:creator><![CDATA[Suyog Kokaje]]></dc:creator>
            <pubDate>Sat, 21 Mar 2026 17:34:37 GMT</pubDate>
            <atom:updated>2026-03-21T17:34:37.678Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BBPzcvrOC741BWK2tj9x1w.png" /></figure><p>In today’s fast paced world, self-improvement often feels overwhelming. Whether you’re trying to get healthier, become more productive, or build a new skill, there are countless variables pulling your attention in different directions. The result is often confusion, inconsistency, and slow or even invisible progress.</p><p>But there’s a simpler, more effective way to approach growth: <strong>freeze time and change one thing at a time.</strong></p><h3>Understanding the Idea of “Freezing Time”</h3><p>Freezing time isn’t about literally stopping the clock. It’s about mentally pausing the complexity of your life and <strong>holding everything constant except one variable</strong>.</p><p>Imagine running a controlled experiment:</p><ul><li>You keep all conditions the same</li><li>You adjust just one factor</li><li>You observe the outcome</li></ul><p>This method strips away noise and gives you clear, reliable insights into what actually works.</p><h3>Why Most People Struggle to Improve</h3><p>One of the biggest mistakes in self-improvement is trying to change too many things at once.</p><p>You’ve probably seen or experienced this:</p><ul><li>Starting a new diet, workout plan, and sleep routine all together</li><li>Testing multiple productivity hacks at the same time</li><li>Overhauling your goals, tools, and strategies overnight</li></ul><p>When results show up or don’t you’re left guessing. What worked? What didn’t? There’s no clarity.</p><p>By focusing on one change at a time, you:</p><ul><li>Gain precise understanding</li><li>Learn faster from real feedback</li><li>Build systems that actually stick</li><li>Avoid unnecessary frustration</li></ul><h3>How to Apply This Method in Your Life</h3><h3>1. Start With a Clear Goal</h3><p>Define exactly what you want to improve. Avoid vague intentions.</p><p>Instead of saying “I want to be better,” try:</p><ul><li>“I want to improve my focus”</li><li>“I want to increase my energy levels”</li><li>“I want to write every day”</li></ul><p>Clarity at this stage makes everything else easier.</p><h3>2. Hold Everything Else Constant</h3><p>List the factors that influence your goal. Then deliberately keep them unchanged.</p><p>For example, if you’re working on productivity, your variables might include:</p><ul><li>Sleep schedule</li><li>Workspace</li><li>Tools and apps</li><li>Diet</li><li>Daily routine</li></ul><p>Choose one factor to experiment with leave the rest untouched.</p><h3>3. Change One Variable</h3><p>Now introduce a single, intentional adjustment.</p><p>For example:</p><ul><li>Wake up one hour earlier</li><li>Remove social media during work hours</li><li>Use a 25-minute focus timer</li></ul><p>Keep the change small and measurable.</p><h3>4. Observe Without Judgment</h3><p>Give your experiment enough time to produce meaningful results. Avoid jumping to conclusions too quickly.</p><p>Ask yourself:</p><ul><li>Did this improve my situation?</li><li>Did it make things worse?</li><li>Was the effect noticeable or minimal?</li></ul><p>Record what you observe. The goal is not perfection it’s understanding.</p><h3>5. Decide and Move Forward</h3><p>Based on what you learn:</p><ul><li>Keep what works</li><li>Discard what doesn’t</li><li>Refine what shows promise</li></ul><p>Then move on to testing the next variable.</p><h3>A Simple Example</h3><p>Let’s say your goal is to boost your energy.</p><p>Instead of making multiple changes at once, you test one at a time:</p><ul><li><strong>Week 1:</strong> Sleep for 8 hours consistently</li><li><strong>Week 2:</strong> Add morning sunlight exposure</li><li><strong>Week 3:</strong> Cut out late-night screen time</li></ul><p>By the end of this process, you’ll know exactly which change had the biggest impact and which ones didn’t matter as much.</p><h3>How to Get Better at This Approach</h3><h3>Be Patient</h3><p>This method may feel slow at first, but it leads to deeper, more reliable progress over time.</p><h3>Think Like an Experimenter</h3><p>Treat each change as a test, not a judgment of your abilities. You’re gathering data, not proving your worth.</p><h3>Track Your Observations</h3><p>Write things down. Over time, patterns will emerge that you wouldn’t notice otherwise.</p><h3>Resist the Urge to Do Too Much</h3><p>It’s tempting to stack multiple changes when you feel motivated. But doing so reduces clarity and weakens your results.</p><h3>The Deeper Advantage: Self-Awareness</h3><p>As you continue using this method, something powerful happens — you begin to understand yourself at a much deeper level.</p><p>You start to see:</p><ul><li>What truly works for you (not others)</li><li>What boosts your energy and what drains it</li><li>How small, precise changes can create significant results</li></ul><p>This is where real mastery begins not through intensity, but through intentional experimentation.</p><h3>Final Thoughts</h3><p>Freezing time isn’t just a technique it’s a mindset shift.</p><p>In a world full of noise and constant change, the ability to slow things down, isolate variables, and learn deliberately is incredibly powerful.</p><p>Instead of guessing your way forward, you begin to <strong>engineer your own growth</strong>.</p><p>So the next time you want to improve something in your life, resist the urge to change everything at once.</p><p>Pause.</p><p>Simplify.</p><p>Change just one thing.</p><p>And let clarity do the rest.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a21f4f1f5ba4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Going Gopher Mode: Decoding Pub/Sub Pattern]]></title>
            <link>https://medium.com/@suyogkokaje6/going-gopher-mode-decoding-pub-sub-pattern-67c0b3be83c1?source=rss-a5d8e005730------2</link>
            <guid isPermaLink="false">https://medium.com/p/67c0b3be83c1</guid>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[system-design-concepts]]></category>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[pub-sub-pattern]]></category>
            <category><![CDATA[go]]></category>
            <dc:creator><![CDATA[Suyog Kokaje]]></dc:creator>
            <pubDate>Sun, 19 Nov 2023 06:35:44 GMT</pubDate>
            <atom:updated>2023-11-19T06:35:44.074Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/850/1*hLaGPMrWHiF28UHY-omDlQ.jpeg" /></figure><p>Welcome back, readers! Today I have come up with the next article in this series. If you’re new and haven’t caught up on the earlier articles, you can find them right <a href="https://medium.com/@suyogkokaje6">here</a>.</p><p>In this article, we will be going to understand about Pub/Sub pattern. Many of you must be having questions such as</p><ul><li><strong>What is Pub/Sub pattern?</strong></li><li><strong>What are the use cases of Pub/Sub pattern?</strong></li><li><strong>How to implement it using the Golang?</strong></li></ul><p>… and many more. So without any further delay let’s find the answers of your questions.</p><h4>What is Pub/Sub pattern?</h4><p>A pub/sub or publish-subscribe pattern is a messaging pattern in which the publisher (sender) sends messages to subscribers (receivers) by categorizing them into topics or classes. Importantly, the publisher doesn’t need to know the details of any particular subscriber in this messaging pattern.</p><p>Let’s take an example of a social media platform.</p><p><strong>Publisher: </strong>The social media platform posts updates, pictures, and events without knowing exactly who will see each post.</p><p><strong>Subscribers:</strong>Users of the platform can subscribe to specific topics or users they are interested in. For instance, a user might follow a technology page, a favourite celebrity, and a news outlet.</p><p><strong>Messaging Pattern:</strong> The platform distributes posts to different topics or users without tailoring content for individual followers. Posts are categorized by topics, such as technology, entertainment, and news.</p><p><strong>Scenario:</strong> Think of a user who follows a technology page. When the page posts updates or news about the latest gadgets, the subscriber automatically receives these updates in their feed. The platform manages the distribution without the need for the publisher to know each user’s specific interests.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FIcOFwawKUJHpUEAaVjD5A.png" /><figcaption>Pub/Sub Pattern</figcaption></figure><h4>Use cases of Pub/Sub pattern:</h4><ol><li><strong>Asynchronous Workflow: </strong>It<strong> </strong>is well-suited for building asynchronous workflows where components need to communicate without blocking each other.</li><li><strong>Decoupling: </strong>It enables loose coupling between components, allowing them to work independently and evolve separately.</li><li><strong>Load Balancing: </strong>It can distribute the load across multiple instances of subscribers, enabling efficient utilisation of resources.</li><li><strong>Deferred Processing: </strong>It allows for deferred or delayed processing of messages, enabling efficient resource utilisation and handling of workloads.</li><li><strong>Data Streaming: </strong>It<strong> </strong>facilitates real-time data streaming and enables data-driven applications that require continuous updates.</li></ol><h4>Key Implementation of Pub/Sub patterns:</h4><p>Let’s start with the <strong><em>message</em></strong> structure. Each message will have multiple attributes including topic and body .</p><pre>type Message struct {<br>    topic string<br>    body string<br>}</pre><p>Next is the <strong><em>subscriber</em></strong> structure. Subscriber should have an id for identification, a messages channel to receive messages, a topics map to track subscribed topics, and an active flag indicating its status. The mutex ensures safe concurrent access to the subscriber&#39;s data.</p><pre>type Subscriber struct {<br>    id string <br>    messages chan* Message <br>    topics map[string]bool <br>    active bool <br>    mutex sync.RWMutex <br>}</pre><p>Last is the <strong><em>broker</em> </strong>structure. It will consist of all the subscribers, and a map to keep track of which users have subscribed to which topic</p><pre>type Broker struct {<br>    subscribers Subscribers <br>    topics map[string]Subscribers <br>    mut sync.RWMutex<br>}</pre><p>Subscribe method subscribes a given topic to a given user.</p><pre>func (b *Broker) Subscribe(s *Subscriber, topic string) {<br>    b.mut.Lock()<br>    defer b.mut.Unlock()<br>    if  b.topics[topic] == nil {<br>        b.topics[topic] = Subscribers{}<br>    }<br>    s.AddTopic(topic)<br>    b.topics[topic][s.id] = s<br>}</pre><p>It uses a mutex for thread safety, initializes the topic if it doesn’t exist, associates the topic with the Subscriber, and adds the Subscriber to the list of subscribers for that topic in the broker’s internal data structure.</p><p>Publish method publishes the given message to the a given topic.</p><pre>func (b *Broker) Publish(topic string, msg string) {<br>    b.mut.RLock()<br>    bTopics := b.topics[topic]<br>    b.mut.RUnlock()<br>    for _, s := range bTopics {<br>        m:= NewMessage(msg, topic)<br>        if !s.active{<br>            return<br>        }<br>        go (func(s *Subscriber){<br>            s.Signal(m)<br>        })(s)<br>    }<br>}</pre><p>It acquires a read lock on the broker’s mutex to ensure concurrent access safety, retrieves the list of subscribers for the given topic, and releases the lock. It then iterates through the subscribers, creating a new message with the provided content and topic for each. If a subscriber is inactive, the message is not sent to that subscriber. Concurrently, each subscriber is signaled with the message using a Goroutine, ensuring asynchronous communication with the subscribers.</p><p>These are the essential structures and methods you will need during the implementation of Pub/Sub pattern. It’s important to note that this isn’t a comprehensive implementation but rather the essential elements needed for the pattern.</p><p>If you want to see the comprehensive implementation of Pub/Sub pattern then here is the link.</p><p><strong>GitHub repository</strong>: <a href="https://github.com/suyogkokaje/go_PubSub"><strong><em>https://github.com/suyogkokaje/go_PubSub</em></strong></a></p><p>The Pub/Sub pattern proves beneficial in Golang as it enables various components within an application to communicate and collaborate without tight coupling. This flexibility facilitates the creation of modular, scalable and easy-to-maintain code, providing developers with a more efficient and adaptable programming approach.</p><p>I hope now some your questions are answered through this article. I am restricting myself here to keep the the article concise. But, if you’re eager to dive deeper into this topic then there is so much to explore. This article is just a starting point. Thank you for staying with me. See you seen in the next article!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=67c0b3be83c1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Going Gopher Mode: Implementing Concurrency and Parallelism-3]]></title>
            <link>https://medium.com/@suyogkokaje6/going-gopher-mode-implementing-concurrency-and-parallelism-3-8962ab409586?source=rss-a5d8e005730------2</link>
            <guid isPermaLink="false">https://medium.com/p/8962ab409586</guid>
            <category><![CDATA[concurrency]]></category>
            <category><![CDATA[implementation]]></category>
            <category><![CDATA[parallelism]]></category>
            <category><![CDATA[go]]></category>
            <category><![CDATA[golang]]></category>
            <dc:creator><![CDATA[Suyog Kokaje]]></dc:creator>
            <pubDate>Fri, 03 Nov 2023 03:25:04 GMT</pubDate>
            <atom:updated>2023-11-03T03:25:04.430Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/850/1*hLaGPMrWHiF28UHY-omDlQ.jpeg" /></figure><p>Hello, readers! It’s been a while. I am here with the next and most probably the final article on the topic of <strong>Concurrency and Parallelism (</strong>though who knows, there might be more in the future :p <strong>)</strong>.</p><p>In the initial article, we explored the fundamental concepts of concurrency and parallelism, laying the groundwork for understanding the magic that Go brings to the table. Then, in the second part of our series, we took a closer look at Goroutines and Channels, two of Go’s most powerful tools for managing concurrent tasks and communication between them. If you’re new and haven’t read the previous articles, don’t worry. You can find those articles here :</p><ol><li><a href="https://medium.com/@suyogkokaje6/going-gopher-mode-introduction-to-concurrency-and-parallelism-1-246d21ebd13f"><strong><em>Going Gopher Mode: Introduction to Concurrency and Parallelism -1</em></strong></a></li><li><a href="https://medium.com/@suyogkokaje6/going-gopher-mode-goroutines-and-channel-935fc6714dd0"><strong><em>Going Gopher Mode: Goroutines and Channels -2</em></strong></a></li></ol><p>Now, in this third article, we’re ready to take things to the next level. We’ll be diving into the practical side of things, exploring the implementation of concurrency and parallelism using goroutines and channels. So, let’s roll up your sleeves and get started!</p><p>To illustrate the ideas of concurrency and parallelism, we’ll take a straightforward example. We’ll calculate the sum of numbers starting from 1 to some large number. This example will help us understand how concurrency and parallelism work in practice.</p><h4><strong>Sequential Execution:</strong></h4><pre>package main<br><br>import &quot;fmt&quot;<br><br>func sumNumbers(n int) int {<br>    sum := 0<br>    for i := 1; i &lt;= n; i++ {<br>        sum += i<br>    }<br>    return sum<br>}<br><br>func main() {<br>    n := 1000000 <br>    result := sumNumbers(n)<br>    fmt.Printf(&quot;Sum of numbers from 1 to %d: %d\n&quot;, n, result)<br>}</pre><ul><li>Here, you have a simple sequential implementation. It calculates the sum of numbers from 1 to n using a loop.</li><li>There is no concurrency or parallelism in this version, so the calculation is done sequentially in a single Goroutine.</li><li>This is the simplest and most straightforward way to carry out the task but it might not make the most of the power of multi-core processors.</li></ul><h4>Concurrent Execution:</h4><pre>package main<br><br>import (<br>    &quot;fmt&quot;<br>    &quot;sync&quot;<br>)<br><br>func sumNumbersConcurrently(n int, numGoroutines int) int {<br>    var wg sync.WaitGroup<br>    ch := make(chan int, numGoroutines)<br>    chunkSize := n / numGoroutines<br><br>    for i := 0; i &lt; numGoroutines; i++ {<br>        start := i * chunkSize + 1<br>        end := (i + 1) * chunkSize<br>        if i == numGoroutines-1 {<br>            end = n<br>        }<br><br>        wg.Add(1)<br>        go func(start, end int) {<br>            defer wg.Done()<br>            sum := 0<br>            for j := start; j &lt;= end; j++ {<br>                sum += j<br>            }<br>            ch &lt;- sum<br>        }(start, end)<br>    }<br><br>    go func() {<br>        wg.Wait()<br>        close(ch)<br>    }()<br><br>    totalSum := 0<br>    for partialSum := range ch {<br>        totalSum += partialSum<br>    }<br><br>    return totalSum<br>}<br><br>func main() {<br>    n := 1000000 <br>    numGoroutines := 4 <br>    result := sumNumbersConcurrently(n, numGoroutines)<br>    fmt.Printf(&quot;Sum of numbers from 1 to %d: %d\n&quot;, n, result)<br>}</pre><ul><li>In concurrent execution, we introduced concurrency by splitting the problem into smaller chunks and calculating each chunk in a separate Goroutine.</li><li>It uses a <strong><em>sync.WaitGroup</em></strong> to wait for all Goroutines to complete their calculations before summing up the results.</li><li>The work is divided into <strong><em>numGoroutines</em></strong> parts, with each Goroutine responsible for a portion of the total range. The use of a Goroutine pool allows for better CPU utilization.</li><li>It uses a channel to send and receive partial sums from the Goroutines, which allows for synchronization and avoids race conditions.</li></ul><h4>Parallel Execution:</h4><pre>package main<br><br>import (<br>    &quot;fmt&quot;<br>    &quot;runtime&quot;<br>    &quot;sync&quot;<br>)<br><br>func sumNumbersParallel(n int, numWorkers int) int {<br>    var wg sync.WaitGroup<br>    ch := make(chan int, numWorkers)<br>    chunkSize := n / numWorkers<br><br>    for i := 0; i &lt; numWorkers; i++ {<br>        start := i * chunkSize + 1<br>        end := (i + 1) * chunkSize<br>        if i == numWorkers-1 {<br>            end = n<br>        }<br><br>        wg.Add(1)<br>        go func(start, end int) {<br>            defer wg.Done()<br>            sum := 0<br>            for j := start; j &lt;= end; j++ {<br>                sum += j<br>            }<br>            ch &lt;- sum<br>        }(start, end)<br>    }<br><br>    go func() {<br>        wg.Wait()<br>        close(ch)<br>    }()<br><br>    totalSum := 0<br>    for partialSum := range ch {<br>        totalSum += partialSum<br>    }<br><br>    return totalSum<br>}<br><br>func main() {<br>    n := 1000000 <br>    numWorkers := 4 <br>    numCores := 2 <br>    runtime.GOMAXPROCS(numCores) <br>    result := sumNumbersParallel(n, numWorkers)<br>    fmt.Printf(&quot;Sum of numbers from 1 to %d: %d\n&quot;, n, result)<br>}</pre><ul><li>In parallel execution, we introduced parallelism by setting the number of CPU cores explicitly using <strong><em>runtime.GOMAXPROCS.</em></strong></li><li>Similar to the concurrent execution, it divides the work into smaller chunks and calculates each chunk in a separate Goroutine.</li><li>However, unlike the concurrent execution, the number of CPU cores that can be used for Goroutines is explicitly set to numCores, which means that the Goroutines can run in parallel on different CPU cores.This can lead to better performance on multi-core systems.</li><li>It still uses a Channel and a s<strong><em>ync.WaitGroup</em></strong> for synchronization, similar to the concurrency version.</li></ul><p>As we wrap up this article, we’ve explored the foundations of concurrency and parallelism in Go, with a practical example to drive the point home. We hope you now have a better understanding of how Goroutines and Channels can turbocharge your applications by leveraging the full potential of your hardware.</p><p>The journey into the realm of Go programming doesn’t end here. There’s still much more to discover, and we’ll continue to explore the ins and outs of this fascinating language in our upcoming articles.</p><p>Until next time, happy coding and keep embracing the Go way!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8962ab409586" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Going Gopher Mode: Goroutines and Channel —]]></title>
            <link>https://medium.com/@suyogkokaje6/going-gopher-mode-goroutines-and-channel-935fc6714dd0?source=rss-a5d8e005730------2</link>
            <guid isPermaLink="false">https://medium.com/p/935fc6714dd0</guid>
            <category><![CDATA[channel]]></category>
            <category><![CDATA[go]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[goroutines]]></category>
            <dc:creator><![CDATA[Suyog Kokaje]]></dc:creator>
            <pubDate>Sat, 21 Oct 2023 06:05:05 GMT</pubDate>
            <atom:updated>2023-10-21T06:07:05.611Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Going Gopher Mode: Goroutines and Channels -2</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/850/1*hLaGPMrWHiF28UHY-omDlQ.jpeg" /></figure><p>Welcome back, readers! We’re continuing with the next article in this series. If you’re new and haven’t read the previous article, don’t worry. You can find it <a href="https://medium.com/@suyogkokaje6/going-gopher-mode-introduction-to-concurrency-and-parallelism-1-246d21ebd13f">here</a>.</p><p>In this article, we’re going to dive into <strong>Goroutines</strong> and <strong>Channels</strong>. We’ll also look at some code snippets to help you grasp these concepts better. Are you all set? Let’s get started!</p><h4><strong>What is Goroutine?</strong></h4><p>A <strong>Goroutine</strong> is an independent function that executes simultaneously in some separate lightweight threads managed by Go. Golang provides it to support concurrency in Go.</p><p>Every program contains at least a single <strong>Goroutine</strong> and that Goroutine is known as the <strong>main Goroutine</strong>. All the Goroutines are working under the main Goroutines if the main Goroutine terminated, then all the goroutine present in the program also terminated. Goroutine always works in the background.</p><h4><strong>How to Create a Goroutine?</strong></h4><p>After reading this much, you might be eager to create a Goroutine and dive into the action, right?</p><p>Here is an example of what a <strong>Goroutine</strong> looks like:</p><pre>package main<br><br>import (<br> &quot;fmt&quot;<br> &quot;time&quot;<br>)<br><br>func main() {<br> go gopher()<br> time.Sleep(1 * time.Second)<br> goodbye()<br>}<br><br>func gopher() {<br> fmt.Println(&quot;Hello, I am Gopher!&quot;)<br>}<br><br>func gotime() {<br> fmt.Println(&quot;It&#39;s Go time!&quot;)<br>}</pre><p>Let’s understand the steps involved here:</p><ol><li>In this example, first, the <strong>main Goroutine</strong> starts.</li><li>Then it invokes the <strong>gopher()</strong> function, and the <strong>gopher Goroutine</strong> starts.</li><li>After the <strong>gopher Goroutine</strong> finishes its operation, the <strong>main Goroutine</strong> waits for 1 second and invokes the gotime() function.</li><li>If you omit the time function in main, then it will exit before the <strong>gopher()</strong> finishes its execution.</li></ol><p>The output of the above example will look like this:</p><pre>Hello, I am Gopher!<br>It&#39;s Go time!</pre><p>Now try running it without using <strong><em>time.Sleep()</em></strong>. Now you can only see</p><pre>It&#39;s Go time!</pre><p>This is because, after adding the <strong><em>time.Sleep()</em></strong>, the <strong>gopher()</strong> routine is able to finish its execution before the main exits.</p><p>Using <strong><em>time.Sleep()</em></strong> for 1 second worked in our case. Blocking a method for 1 second may not pose issues in small-scale applications. However, in a production environment where every millisecond counts, a large volume of concurrent requests can lead to significant problems and performance bottlenecks.</p><p>The solution to this problem lies in using <strong>WaitGroups</strong>. You can use <strong>WaitGroups</strong> to wait for multiple Goroutines to finish. A <strong>WaitGroup</strong> blocks the execution of a function until its internal counter becomes 0.</p><p>Here’s an example illustrating how to use <strong>WaitGroups</strong>:</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> wg.Add(2)<br> go gopher(&amp;wg)<br> go gotime(&amp;wg)<br> wg.Wait()<br>}<br><br>func gopher(wg *sync.WaitGroup) {<br> defer wg.Done()<br> fmt.Println(&quot;Hello, I am Gopher!&quot;)<br>}<br><br>func gotime(wg *sync.WaitGroup) {<br> defer wg.Done()<br> fmt.Println(&quot;It&#39;s Go time!&quot;)<br>}</pre><p><strong>Output:</strong></p><pre>Hello, I am Gopher!<br>It&#39;s Go time!</pre><p>You’ll notice that the output of this program is identical to the previous one. But in this case we are not blocking the main.</p><ol><li><strong><em>wg.Add(int)</em></strong>: This method indicates the number of Goroutines to wait. In the above code, I have provided 2 for 2 different Goroutines. Hence the internal counter wait becomes 2.</li><li><strong><em>wg.Wait()</em></strong>: This method blocks the execution of code until the internal counter becomes 0.</li><li><strong><em>wg.Done()</em></strong>: This will reduce the internal counter value by 1.</li></ol><p>Great, you’ve successfully covered the first part of this article, which focused on <strong>Goroutines</strong>. If you’ve grasped the Goroutine concept, that’s fantastic. In case you found it challenging, don’t worry, you can always go back and review the above content. Now, let’s shift our attention to the second half of the article, where we’ll explore <strong>Channels</strong>.</p><h4>What are Channels?</h4><p>In Go, a <strong>channel</strong> is a medium through which a Goroutine communicates with another Goroutine.</p><p>By default channel is bidirectional. Bidirectional communication means that one Goroutine will send a message and the other will read it. Sends and receives are blocking. Code execution will be stopped until the write and read are done successfully.</p><p>Channels provide a way for Goroutines to send and receive data in a thread-safe manner.</p><p>There are primarily two types of channels in Go:</p><p><strong>Unbuffered Channels</strong> :</p><ul><li>Unbuffered channels are also known as synchronous channels.</li><li>When you send a value into an unbuffered channel, it will block until another Goroutine is ready to receive that value from the same channel.</li><li>This synchronous behavior ensures that there is a direct communication between the sender and receiver. It’s like passing a baton in a relay race; one Goroutine sends data, and the other receives it immediately.</li></ul><p><strong>Buffered Channels</strong> :</p><ul><li>Buffered channels allow for asynchronous communication between Goroutines.</li><li>When you create a buffered channel with a specific capacity, you can send up to capacity values into the channel without blocking. Once the channel is full, sending additional values will block until some values are received.</li><li>Buffered channels are like a mailbox with a limited number of slots. You can drop your message in the mailbox, and someone can pick it up when they are ready.</li></ul><p>Now take a quick look at the syntax of declaring the Go Channels:</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>    // Unbuffered Channel<br>    unbufferedCh := make(chan int)<br><br>    // Sender for unbuffered channel<br>    wg.Add(1)<br>    go func() {<br>        defer wg.Done()<br>        fmt.Println(&quot;Sender for unbuffered channel: Sending 42&quot;)<br>        unbufferedCh &lt;- 42<br>        fmt.Println(&quot;Sender for unbuffered channel: Sent 42&quot;)<br><br>        // Close the unbuffered channel when done sending<br>        close(unbufferedCh)<br>    }()<br><br>    // Receiver for unbuffered channel<br>    wg.Add(1)<br>    go func() {<br>        defer wg.Done()<br>        fmt.Println(&quot;Receiver for unbuffered channel: Receiving...&quot;)<br>        for value := range unbufferedCh {<br>            fmt.Printf(&quot;Receiver for unbuffered channel: Received %d\n&quot;, value)<br>        }<br>    }()<br><br>    // Buffered Channel<br>    bufferedCh := make(chan string, 2)<br><br>    // Sender for buffered channel<br>    wg.Add(1)<br>    go func() {<br>        defer wg.Done()<br>        fmt.Println(&quot;Sender for buffered channel: Sending &#39;Hello&#39;&quot;)<br>        bufferedCh &lt;- &quot;Hello&quot;<br>        fmt.Println(&quot;Sender for buffered channel: Sent &#39;Hello&#39;&quot;)<br><br>        fmt.Println(&quot;Sender for buffered channel: Sending &#39;World&#39;&quot;)<br>        bufferedCh &lt;- &quot;World&quot;<br>        fmt.Println(&quot;Sender for buffered channel: Sent &#39;World&quot;)<br><br>        // Close the buffered channel when done sending<br>        close(bufferedCh)<br>    }()<br><br>    // Receiver for buffered channel<br>    wg.Add(1)<br>    go func() {<br>        defer wg.Done()<br>        fmt.Println(&quot;Receiver for buffered channel: Receiving...&quot;)<br>        for value := range bufferedCh {<br>            fmt.Printf(&quot;Receiver for buffered channel: Received &#39;%s&#39;\n&quot;, value)<br>        }<br>    }()<br><br>    wg.Wait()<br>}</pre><p>Above code snippet showcases the use of both <strong>unbuffered</strong> and <strong>buffered</strong> channels for concurrent communication between Goroutines.</p><p>It sets up a <strong>WaitGroup</strong> for synchronization, creates an unbuffered channel for integer communication, where a sender sends the value 42 and closes the channel, while a receiver continuously receives and prints values.</p><p>It also establishes a buffered channel for string communication, allowing two values to be sent before blocking the sender, with a sender and receiver for string values.</p><p>The program ensures all Goroutines complete their tasks by using WaitGroup. This code illustrates the fundamental principles of Go channels, including blocking behavior and channel closure.</p><p>Great news! We’ve come to the conclusion. Throughout this article, we’ve explored the fundamental concepts of <strong>Goroutines</strong> and <strong>Channels</strong>. It’s important to note that this is just a basic introduction, and there’s a lot more to delve into on this topic. However, to keep this article from becoming overly lengthy, we’ve confined our discussion to this extent.</p><p>Now that we are aware about Goroutines and Channels in the next article of this series we will see <strong>concurrency</strong> and <strong>parallelism</strong> in action.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=935fc6714dd0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Going Gopher Mode: Introduction to Concurrency and Parallelism — 1]]></title>
            <link>https://medium.com/@suyogkokaje6/going-gopher-mode-introduction-to-concurrency-and-parallelism-1-246d21ebd13f?source=rss-a5d8e005730------2</link>
            <guid isPermaLink="false">https://medium.com/p/246d21ebd13f</guid>
            <category><![CDATA[go]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[concurrency]]></category>
            <category><![CDATA[parallelism]]></category>
            <dc:creator><![CDATA[Suyog Kokaje]]></dc:creator>
            <pubDate>Sat, 14 Oct 2023 10:32:30 GMT</pubDate>
            <atom:updated>2023-10-14T10:56:21.605Z</atom:updated>
            <content:encoded><![CDATA[<h3>Going Gopher Mode: Introduction to Concurrency and Parallelism -1</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/850/1*hLaGPMrWHiF28UHY-omDlQ.jpeg" /></figure><p>Greetings, dear readers! It’s a pleasure to welcome you to my inaugural article of this series. If I happen to make any missteps along the way, your understanding and guidance would be greatly appreciated.</p><p>In this article, we’ll delve into key concepts in the <strong>Go</strong> programming language <em>(</em><strong><em>Golang</em></strong><em>)</em> that are fundamental for your future endeavors. You may have encountered these concepts before, and this post aims to provide you with a clearer understanding, shedding light on aspects you may have found confusing in the past.</p><p>Indeed, you’ve guessed correctly! Today, we’ll discuss about <strong>concurrency and parallelism</strong> in an easy-to-understand way. Don’t worry if these terms are unfamiliar to you; this is the perfect starting point to learn about them.</p><h3>What is Concurrency?</h3><p>Concurrency is a bit like conducting an orchestra where many musicians play their instruments together, creating a harmonious performance. It means breaking down a program into smaller parts that can work at the same time, even overlapping. The idea is to make things more efficient and responsive, especially when tasks can happen at the same time without needing a specific order.</p><p>Concurrency has lots of advantages, but it also brings some difficulties. Think of it like a busy marketplace with different vendors selling their products. Each vendor is like a task happening at the same time. The tricky part is keeping things organized and preventing chaos. In concurrent programming, problems like race conditions, deadlocks, and resource conflicts can occur if you don’t manage them correctly.</p><h3>What is Parallelism?</h3><p>Parallelism involves breaking down tasks into smaller parts and having them carried out simultaneously on separate processors or cores. Think of it like a fast-moving assembly line, where each worker plays a role in the production process, leading to quicker results. Parallel programs make use of multiple cores to significantly speed up tasks, allowing them to be finished more quickly.</p><p>After reading the answers to the previous questions, you might be wondering if <strong>concurrency</strong> and <strong>parallelism </strong>are alike. Well, if you’re thinking they are, you’re not quite right. Let’s understand the difference with very simple example.</p><p><strong>Concurrency</strong> is like when you’re jogging, and you stop for a moment to tie your shoelaces. You’re taking care of two things, running and tying your laces, but not at the exact same time.</p><p><strong>Parallelism</strong> is when you’re jogging and listening to music with earphones. Here, you’re doing both things at the very same time, no pause. It’s like multitasking while jogging.</p><p>I hope this clears up the concepts for you.</p><p>Knowing the differences between concurrency and parallelism is important because it helps you decide which method to use depending on the problem and your computer’s capabilities. Now, let’s look at some important things to think about when you’re picking between these two approaches:</p><h4>1. Granularity Of Tasks</h4><ul><li>In concurrency, tasks can be very small and flexible, which means you can handle them in a more adaptable way.</li><li>In parallelism, tasks are usually bigger, focusing on breaking work into larger pieces that can be done at the same time.</li></ul><h4>2. Resource Utilization</h4><ul><li>Concurrency is good when you don’t have many resources because it helps tasks make progress even with limited resources.</li><li>Parallelism works best when you have plenty of computing power, like many cores or processors.</li></ul><h4>3. Overhead And Synchronization</h4><ul><li>Concurrency introduces additional overhead and synchronization mechanisms to ensure proper coordination between tasks.</li><li>Parallelism, while minimizing coordination overhead, may require synchronization for shared resources to avoid data races and conflicts.</li></ul><h4><strong>“Concurrency is about dealing with lots of things at once. Parallelism is about doing lots of things at once.” — Rob Pike</strong></h4><p>And with that, we’ve reached the end of this article. I want to express my gratitude for your patience and for staying with me until the very end. In the upcoming article in this series, we will dive into practical implementations of <strong>concurrency</strong> and <strong>parallelism</strong>, using the power of <strong>goroutines</strong> and <strong>channels</strong> to illustrate these concepts.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=246d21ebd13f" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>