<?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 Vaibhav Jha on Medium]]></title>
        <description><![CDATA[Stories by Vaibhav Jha on Medium]]></description>
        <link>https://medium.com/@vaibhavjha?source=rss-a3b294fdba5b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*ptaQPEDi0jvKPUi_.</url>
            <title>Stories by Vaibhav Jha on Medium</title>
            <link>https://medium.com/@vaibhavjha?source=rss-a3b294fdba5b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 16:19:35 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@vaibhavjha/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[Creating Your Own WaitGroup in Go]]></title>
            <link>https://blog.stackademic.com/creating-your-own-waitgroup-in-go-b2c80178d6d0?source=rss-a3b294fdba5b------2</link>
            <guid isPermaLink="false">https://medium.com/p/b2c80178d6d0</guid>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Vaibhav Jha]]></dc:creator>
            <pubDate>Mon, 13 May 2024 07:01:33 GMT</pubDate>
            <atom:updated>2024-05-14T23:50:10.950Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SctrClck1CChJqCyyXLj7w.jpeg" /></figure><h3>A short primer on WaitGroups</h3><p>A WaitGroup in Go is a synchronization mechanism that can be used to wait for a collection of goroutines to finish the execution. This is a handy primitive that is helpful when you have multiple concurrent operations that you want to complete before proceeding further.</p><p>Here is how WaitGroup works:</p><ul><li><strong>Add</strong> — Before launching a goroutine, the <strong>Add </strong>method is called to indicate that the gorutine has started. The Add method accepts an integer which signifies the number of goroutines to wait for.</li><li><strong>Done</strong> — After the goroutine is finished, it calls the Done method to mark its completion.</li><li><strong>Wait</strong> — A Call to Wait method blocks until all the goroutines are finished.</li></ul><p>Here is a simple example to showcase its usage:</p><pre>package main<br><br>import (<br>	&quot;fmt&quot;<br>	&quot;sync&quot;<br>	&quot;time&quot;<br>)<br><br>func work(i int, wg *sync.WaitGroup) {<br>	fmt.Println(&quot; work &quot;, i, &quot; started.&quot;)<br>	time.Sleep(1 * time.Second)<br>	fmt.Println(&quot; work &quot;, i, &quot; ended.&quot;)<br>	wg.Done()<br>}<br><br>func main() {<br>	wg := sync.WaitGroup{}<br>	for i := 0; i &lt; 2; i++ {<br>		wg.Add(1)<br>		go work(i, &amp;wg)<br>	}<br><br>	wg.Wait()<br>}</pre><p>In this scenario, the work function is called twice concurrently. Each instance of the work function pauses for a second before invoking wg.Done, signalling its completion. Meanwhile, in the main goroutine, the wg.Wait call suspends execution until all goroutines have finished.</p><h3>Implementing our own WaitGroup from scratch</h3><p>Given our understanding of WaitGroup’s behaviour in Go, let’s build one from the ground up. We’ll use a condition variable for this implementation. After we’ve developed our custom WaitGroup, we’ll update the previously discussed example to utilize our new implementation.</p><h4>Define Custom Wait Group struct:</h4><pre>type CustomWaitGroup struct {<br>	counter int // number of concurrent execution<br>	cond    *sync.Cond<br>}</pre><p>The <strong>CustomWaitGroup</strong> has two properties, <strong>counter</strong> and <strong>cond</strong>. counter signifies the number of concurrent executions to wait for. The cond is a conditional Variable on top of a normal mutex lock.</p><h4>Implement a constructor to create an instance of CustomWaitGroup</h4><pre>func NewWaitGroup() *CustomWaitGroup {<br>	return &amp;CustomWaitGroup{cond: sync.NewCond(&amp;sync.Mutex{})}<br>}</pre><h4>Implement the Add method:</h4><p>The Add method in CustomWaitGroup increases the counter by a specified integer value. Initially set to zero, this counter is incremented by the value passed to the method.</p><pre>func (wg *CustomWaitGroup) Add(n int) {<br>	wg.cond.L.Lock()<br>	wg.counter += n<br>	wg.cond.L.Unlock()<br>}</pre><h4>Implement the Done method</h4><p>The Done method reduces the counter by one, indicating the completion of a goroutine&#39;s execution. Following the decrement, it invokes the Signal method on the condition variable.</p><pre>func (wg *CustomWaitGroup) Done() {<br>	wg.cond.L.Lock()<br>	wg.counter--<br>	wg.cond.Signal()<br>	wg.cond.L.Unlock()<br>}</pre><h4>Implement the Wait method</h4><p>When the counter is non-zero, the Wait method pauses and halts the executing goroutine. This suspension is facilitated through the condition variable within the CustomWaitGroup.</p><pre>func (wg *CustomWaitGroup) Wait() {<br>	wg.cond.L.Lock()<br>	for wg.counter &gt; 0 {<br>		wg.cond.Wait()<br>	}<br>	wg.cond.L.Unlock()<br>}</pre><p>Having developed our custom wait group, mirroring the functionality of the wait group found in the sync package, let’s now adapt the code from the previous example to use this new implementation.</p><pre>package main<br><br>import (<br>	&quot;fmt&quot;<br>	&quot;sync&quot;<br>	&quot;time&quot;<br>)<br><br>type CustomWaitGroup struct {<br>	counter int // number of concurrent execution<br>	cond    *sync.Cond<br>}<br><br>func NewWaitGroup() *CustomWaitGroup {<br>	return &amp;CustomWaitGroup{cond: sync.NewCond(&amp;sync.Mutex{})}<br>}<br><br>func (wg *CustomWaitGroup) Add(n int) {<br>	wg.cond.L.Lock()<br>	wg.counter += n<br>	wg.cond.L.Unlock()<br>}<br><br>func (wg *CustomWaitGroup) Done() {<br>	wg.cond.L.Lock()<br>	wg.counter--<br>	wg.cond.Signal()<br>	wg.cond.L.Unlock()<br>}<br><br>func (wg *CustomWaitGroup) Wait() {<br>	wg.cond.L.Lock()<br>	for wg.counter &gt; 0 {<br>		wg.cond.Wait()<br>	}<br>	wg.cond.L.Unlock()<br>}<br><br>func work(i int, wg *CustomWaitGroup) {<br>	fmt.Println(&quot; work &quot;, i, &quot; started.&quot;)<br>	time.Sleep(1 * time.Second)<br>	fmt.Println(&quot; work &quot;, i, &quot; ended.&quot;)<br>	wg.Done()<br>}<br><br>func main() {<br>	wg := NewWaitGroup()<br>	for i := 0; i &lt; 2; i++ {<br>		wg.Add(1)<br>		go work(i, wg)<br>	}<br><br>	wg.Wait()<br>}</pre><h3>Stackademic 🎓</h3><p>Thank you for reading until the end. Before you go:</p><ul><li>Please consider <strong>clapping</strong> and <strong>following</strong> the writer! 👏</li><li>Follow us <a href="https://twitter.com/stackademichq"><strong>X</strong></a><strong> | </strong><a href="https://www.linkedin.com/company/stackademic"><strong>LinkedIn</strong></a><strong> | </strong><a href="https://www.youtube.com/c/stackademic"><strong>YouTube</strong></a><strong> | </strong><a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Discord</strong></a></li><li>Visit our other platforms: <a href="https://plainenglish.io/"><strong>In Plain English</strong></a><strong> | </strong><a href="https://cofeed.app/"><strong>CoFeed</strong></a><strong> | </strong><a href="https://venturemagazine.net/"><strong>Venture</strong></a><strong> | </strong><a href="https://blog.cubed.run/"><strong>Cubed</strong></a></li><li>Tired of blogging platforms that force you to deal with algorithmic content? Try <a href="https://differ.blog/"><strong>Differ</strong></a></li><li>More content at <a href="https://stackademic.com/"><strong>Stackademic.com</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b2c80178d6d0" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/creating-your-own-waitgroup-in-go-b2c80178d6d0">Creating Your Own WaitGroup in Go</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Designing write preferring Readers-Writer lock]]></title>
            <link>https://vaibhavjha.medium.com/designing-write-preferring-readers-writer-lock-5526434fe604?source=rss-a3b294fdba5b------2</link>
            <guid isPermaLink="false">https://medium.com/p/5526434fe604</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[software]]></category>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[golang]]></category>
            <dc:creator><![CDATA[Vaibhav Jha]]></dc:creator>
            <pubDate>Mon, 06 May 2024 16:14:49 GMT</pubDate>
            <atom:updated>2024-05-13T06:55:38.995Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GG0riqHT2uL8gmRF4c4hLQ.jpeg" /></figure><p>In the previous <a href="https://medium.com/@vaibhavjha/using-readers-writer-locks-to-boost-concurrency-in-go-applications-98ef87f4eea8">article</a>, we looked at how readers-writer lock helps multiple readers access information simultaneously but ensure only one writer can make changes at a time. We also looked at an example that uses readers-writer lock implementation provided by Golang standard library.</p><p>How about we implement our own version of readers-writer lock? Before we start with the implementation, let’s understand the difference between Read preferring and write preferring and how these two terms are relevant in this context.</p><h3>Priority of Readers-Writer Lock</h3><p>There are different versions of the readers-writer lock, each version providing different priority to either readers or writers. Let’s look at them in detail:</p><p><strong>Read Preferring Lock:</strong> The read preferring lock allows for maximum concurrency. In this version, priority is given to reader threads. The writer threads will not be able to acquire the lock even if there is one reader thread present. Usually, readers-writer locks are used in read heavy scenario, so there is a high chance of at least one or more reader thread always acquiring the lock. This results in write starvation.</p><p><strong>Write Preferring Lock: </strong>The write preferring lock gives priority to the writer threads. If a writer thread is waiting for the lock, it guarantees that the lock will be given to writer thread once all the existing reader thread releases the lock. The new readers are given the lock only if there are no writer waiting for the lock. This prevents the write starvation however this limits the concurrency.</p><p><strong>Fair</strong>: Attempts to balance between readers and writers, ensuring that neither readers nor writers starve. This is typically implemented using queues.</p><p>In this article, we will implement a Write preferring Readers writer lock using mutex and condition variable.</p><h3>Implementing the Readers-Writer lock</h3><h4>Step 1: Defining the Structure of the Custom Readers-writer lock</h4><p>To design a write preferred lock, we need following properties:</p><p><strong>readCounter: </strong>Initially set to 0<strong>, </strong>this indicates the number of goroutines that has currently acquired the read lock.</p><p><strong>writeCounter:</strong> Initially set to 0, this indicates the number of goroutines waiting to acquire the write lock.</p><p><strong>writeActive:</strong> initially set to false, this tells us if a resource is currently being updated by writer goroutines.</p><p><strong>cond:</strong> This defines a condition Variable on top of standard mutex lock. This allows us to wait for various type of conditions, suspend the execution, and signaling between the threads.</p><p>Now that we know the properties needed, let’s define the ReadersWriter struct.</p><pre>type ReadersWriter struct {<br>    readCounter int<br>    writeCounter int<br>    writeActive bool<br>    cond *sync.Cond<br>}</pre><h4>Step2: Creation</h4><p>This creates the ReadersWriter with condition variable initialized. The initial value of readCounter and writeCounter is zero, whereas the writeActive flag is set to false.</p><pre>func NewReaderWriter() *ReaderWriter {<br>	return &amp;ReaderWriter{<br>		readCounter:  0,<br>		writeCounter: 0,<br>		writeActive:  false,<br>		cond:         sync.NewCond(&amp;sync.Mutex{}),<br>	}<br>}</pre><h4>Step3: Implementing Read Lock (RLock)</h4><p>If there are no writer goroutines waiting in the queue or any active write lock is acquired, the call to RLock will be successful. Otherwise, the goroutine calling the RLock would be suspended. Once the last writer goroutine releases the write lock, the suspended reader gorutine would wake up and acquire the lock.</p><pre>func (rw *ReaderWriter) RLock() {<br>	rw.cond.L.Lock()<br>	for rw.writeCounter &gt; 0 || rw.writeActive {<br>		rw.cond.Wait()<br>	}<br>	rw.readCounter++<br>	rw.cond.L.Unlock()<br>}</pre><h4>Step 4: Implementing Write Lock (Lock)</h4><p>If the lock is acquired by either reader or writer goroutines, the writer goroutine calling the Lock would be suspended. Once there are no active readers or writer threads in the system acquiring the lock, the suspended Goroutine would wake up and acquire the write lock. The writeActive flag becomes true when a write lock is acquired.</p><pre>func (rw *ReaderWriter) Lock() {<br>	rw.cond.L.Lock()<br>	rw.writeCounter++<br>	for rw.readCounter &gt; 0 || rw.writeActive {<br>		rw.cond.Wait()<br>	}<br>	rw.writeCounter--<br>	rw.writeActive = true<br>	rw.cond.L.Unlock()<br>}</pre><h4>Step 4: Implementing Read Unlock (RUnlock)</h4><p>This decrements the readCounter. When the value of readCounter becomes zero, it means the there are no active readers in the system and signal is broadcasted to all the waiting goroutines. This gives an opportunity to suspended writer gorutines to wake up so that one of them can get hold of the write lock.</p><pre>func (rw *ReaderWriter) RUnlock() {<br>	rw.cond.L.Lock()<br>	rw.readCounter--<br>	for rw.readCounter == 0 {<br>		rw.cond.Broadcast()<br>	}<br>	rw.cond.L.Unlock()<br>}</pre><h4>Step 5: Implementing Write Unlock (Unlock)</h4><p>Unlocking is straightforward. It simply involves setting the writeActive flag to false and signaling all suspended goroutines. This action allows any waiting goroutine for a write lock to obtain it. Otherwise, reader goroutines can acquire the read lock.</p><pre>func (rw *ReaderWriter) Unlock() {<br>	rw.cond.L.Lock()<br>	rw.writeActive = false<br>	rw.cond.Broadcast()<br>	rw.cond.L.Unlock()<br>}</pre><p>That’s it. Our implementation of readers-writer lock is ready. One can use this as a synchronization mechanism in read heavy scenarios. In the example featured in the previous article, you can try using this custom implementation instead of using the one provided in the sync package.</p><p>We explored the concept of readers-writer locks and the differences between read-preferring and write-preferring locks. While read-preferring locks maximize concurrency by prioritizing reader threads, they can lead to write starvation. On the other hand, write-preferring locks prioritize writer threads, ensuring they get access to the resource without waiting for too long.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5526434fe604" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using Readers-Writer Locks to Boost Concurrency in Go Applications]]></title>
            <link>https://vaibhavjha.medium.com/using-readers-writer-locks-to-boost-concurrency-in-go-applications-98ef87f4eea8?source=rss-a3b294fdba5b------2</link>
            <guid isPermaLink="false">https://medium.com/p/98ef87f4eea8</guid>
            <dc:creator><![CDATA[Vaibhav Jha]]></dc:creator>
            <pubDate>Sun, 28 Apr 2024 09:31:53 GMT</pubDate>
            <atom:updated>2024-04-28T09:31:53.692Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UEBY-TdxxUMPGnZUZlufMQ.jpeg" /></figure><p>Imagine you’re tasked with designing an event feed for an IPL match between CSK and MI. Users will connect through a mobile app to receive real-time match updates. For this scenario, let’s assume the backend application is written in Golang and does not use any databases. Instead, the events will be persisted in the application memory itself, represented as a slice of strings.</p><p>we’ll have a match recorder goroutine responsible for updating the content of the feed store, whenever a new event occurs. Mobile clients connect to the server via web socket connections for real-time updates. Each client connection is managed in a separate goroutine. Although there could be millions of people interested in the match, the number of event updates will be relatively low (around 5–10 events per minute).</p><p>Let’s write the code that handles both the client connection and event feed update:</p><pre>package main<br><br>import (<br>	&quot;fmt&quot;<br>	&quot;strconv&quot;<br>	&quot;sync&quot;<br>	&quot;time&quot;<br>)<br><br>func matchRecorder(matchEvents *[]string, mutex *sync.Mutex) {<br>	for i := 0; ; i++ {<br>		mutex.Lock()<br>		*matchEvents = append(*matchEvents, &quot;Match event &quot;+strconv.Itoa(i))<br>		mutex.Unlock()<br>		time.Sleep(200 * time.Millisecond)<br>	}<br>}<br><br>func copyAllEvents(matchEvent *[]string) []string {<br>	allEvents := make([]string, 0, len(*matchEvent))<br>	for _, e := range *matchEvent {<br>		allEvents = append(allEvents, e)<br>	}<br>	return allEvents<br>}<br><br>func clientHandler(matchEvents *[]string, mutex *sync.Mutex, at time.Time) {<br>	for i := 0; i &lt; 100; i++ {<br>		mutex.Lock()<br>		allEvents := copyAllEvents(matchEvents)<br>		mutex.Unlock()<br><br>		timeTaken := time.Since(at)<br><br>		fmt.Println(len(allEvents), &quot;events copied in&quot;, timeTaken)<br>	}<br>}<br><br>func main() {<br>	mutex := sync.Mutex{}<br>	var matchEvents = make([]string, 0, 10000)<br>	for j := 0; j &lt; 10000; j++ {<br>		matchEvents = append(matchEvents, &quot;Match event&quot;)<br>	}<br><br>	go matchRecorder(&amp;matchEvents, &amp;mutex)<br><br>	start := time.Now()<br>	for j := 0; j &lt; 5000; j++ {<br>		go clientHandler(&amp;matchEvents, &amp;mutex, start)<br>	}<br><br>	time.Sleep(100 * time.Second)<br>}</pre><p>In the provided code, matchRecorder updates the matchEvents slice every 200 milliseconds. While updating the event, it acquires the lock and then releases it once the event is added. The clientHandler manages active client connections and calls copyAllEvents, which simulates response generation. This method also acquires the lock while generating the response.</p><p>However, there’s an issue with this implementation. The reader goroutines are merely reading the content of matchEvents, but with the current setup, only one goroutine can read the shared data at a time. Other reader goroutines will wait for their turn until the lock becomes available again. This impacts the system&#39;s throughput, as multiple clients could be served simultaneously instead of just one.</p><p>To address this problem, we can utilize a Readers-Writer Mutex Lock instead of a standard Mutex lock. The readers-writer lock allows concurrent reading of shared memory but only permits a single writer to update the memory. Let’s understand the concept of a readers-writer lock and then modify our approach accordingly.</p><h3>What is a Readers-Writer Lock?</h3><p>A readers-writer lock is a synchronization primitive that solves problems where a data structure is read by multiple threads (or goroutines in the case of Go) and written to by one or few threads. This type of lock makes programs efficient when there is a high ratio of read operations to write operations.</p><p>Golang provides the sync.RWMutex type, which is a readers-writer mutex. This lock allows multiple readers to hold the lock simultaneously, provided no writer holds the lock. on the other hand, a writer can only obtain the lock if no other readers or writers are holding the lock. This design helps to maximize concurrent read access, while still providing safety and consistency when writing data.</p><p>Here’s how it works:</p><ol><li>Read Lock (RLock()) — This method is used when a goroutine needs to read data. Multiple goroutines can acquire the read lock (RLock()) simultaneously, as long as no goroutine holds a write lock. This allows multiple readers to access the data concurrently.</li><li>Read Unlock (RUnlock()) — A goroutine that has finished reading and has previously acquired a read lock must release it by calling RUnlock(). It’s crucial that each RLock() call has a corresponding RUnlock() to avoid deadlocks or other synchronization issues.</li><li>Write Lock (Lock()) — This method is used when a goroutine needs to write data. A write lock is exclusive, meaning that no other goroutine can hold either a read lock or a write lock. The writer will wait until all existing readers and writers have released their locks before it can proceed with obtaining the lock.</li><li>Write Unlock (Unlock()) — After finishing the write operation, the goroutine must call Unlock() to release the write lock, allowing other readers or writers to acquire the lock.</li></ol><h3>Using the Readers-Writer Lock</h3><p>Equipped with knowledge of the readers-writer lock, let’s modify our previous implementation. In the new approach, we’ll utilize RWMutex instead of a standard mutex. This way, all clients can concurrently read from shared memory, thereby increasing overall read throughput.</p><pre>package main<br><br>import (<br>	&quot;fmt&quot;<br>	&quot;strconv&quot;<br>	&quot;sync&quot;<br>	&quot;time&quot;<br>)<br><br>func matchRecorder(matchEvents *[]string, mutex *sync.RWMutex) {<br>	for i := 0; ; i++ {<br>		mutex.Lock()<br>		*matchEvents = append(*matchEvents, &quot;Match event &quot;+strconv.Itoa(i))<br>		mutex.Unlock()<br>		time.Sleep(200 * time.Millisecond)<br>	}<br>}<br><br>func copyAllEvents(matchEvent *[]string) []string {<br>	allEvents := make([]string, 0, len(*matchEvent))<br>	for _, e := range *matchEvent {<br>		allEvents = append(allEvents, e)<br>	}<br>	return allEvents<br>}<br><br>func clientHandler(matchEvents *[]string, mutex *sync.RWMutex, at time.Time) {<br>	for i := 0; i &lt; 100; i++ {<br>		mutex.RLock()<br>		allEvents := copyAllEvents(matchEvents)<br>		mutex.RUnlock()<br><br>		timeTaken := time.Since(at)<br><br>		fmt.Println(len(allEvents), &quot;events copied in&quot;, timeTaken)<br>	}<br>}<br><br>func main() {<br>	mutex := sync.RWMutex{}<br>	var matchEvents = make([]string, 0, 10000)<br>	for j := 0; j &lt; 10000; j++ {<br>		matchEvents = append(matchEvents, &quot;Match event&quot;)<br>	}<br><br>	go matchRecorder(&amp;matchEvents, &amp;mutex)<br><br>	start := time.Now()<br>	for j := 0; j &lt; 5000; j++ {<br>		go clientHandler(&amp;matchEvents, &amp;mutex, start)<br>	}<br><br>	time.Sleep(100 * time.Second)<br>}</pre><p>In this article, we explored using a readers-writer lock in read-heavy scenarios. In a future article, I will guide you through creating a write-preferred readers-writer lock from the ground up.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=98ef87f4eea8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Navigating Race Conditions in Go: A Tale of Feline Financial Planning ]]></title>
            <link>https://vaibhavjha.medium.com/navigating-race-conditions-in-go-a-tale-of-feline-financial-planning-6d3a307d82a6?source=rss-a3b294fdba5b------2</link>
            <guid isPermaLink="false">https://medium.com/p/6d3a307d82a6</guid>
            <dc:creator><![CDATA[Vaibhav Jha]]></dc:creator>
            <pubDate>Sun, 28 Apr 2024 09:25:46 GMT</pubDate>
            <atom:updated>2024-04-28T09:25:46.046Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yl7q7H7iRmvk1uXotlcC0A.jpeg" /></figure><p>In the dynamic cityscape of Delhi, a family of cats resides, with the kittens immersed in play, unaware of the complexities of life. Their parents, however, are forward-thinking and aspire for their offspring to receive a quality education. In order to achieve this, they’ve initiated a savings plan for their kitten’s future college expenses by setting up a joint bank account. The cat parents regularly contribute to this fund, making coordinated efforts to enhance their savings through consistent deposits. In an interesting twist, both the cat mom and dad decide to independently contribute $10 to the account at varying intervals, without prior coordination. They plan to continue this pattern until they have each made 10,000 contributions, following which they intend to review the account balance to better strategize their savings approach.</p><p>This can be modelled by this Golang code:</p><pre>package main<br><br>import (<br>	&quot;fmt&quot;<br>	&quot;sync&quot;<br>)<br><br>type Bank struct {<br>	balance int<br>}<br><br>func newAccount(amount int) *Bank {<br>	return &amp;Bank{balance: 100}<br>}<br><br>func (bank *Bank) depositAmount(amount int, name string, numberOfDeposits int, wg *sync.WaitGroup) {<br>	for range numberOfDeposits {<br>		bank.balance += amount<br>	}<br>	wg.Done()<br>}<br><br>func main() {<br>	bankAccount := newAccount(100)<br>	wg := sync.WaitGroup{}<br><br>	wg.Add(2)<br><br>	numberOfDeposits := 10000<br><br>	go bankAccount.depositAmount(10, &quot;Father Cat&quot;, numberOfDeposits, &amp;wg)<br>	go bankAccount.depositAmount(10, &quot;Mother Cat&quot;, numberOfDeposits, &amp;wg)<br><br>	wg.Wait()<br>	fmt.Printf(&quot;The current account balance is $%d.00\n&quot;, bankAccount.balance)<br>}</pre><p>The bank account is represented by a Bank struct which maintains the current balance. The method depositAmount, when called, increases the bank&#39;s balance by the specified amount for a predetermined number of times, defined as numberOfDeposits.<strong> </strong>In a concurrent setting, both the Father and Mother cat invoke the depositAmount method from their respective goroutines, enabling them to make deposits into the account simultaneously.</p><p>When running the above code multiple times, you may notice that the final balance of the joint bank account varies. This seems puzzling because both Father and Mother cats are consistently depositing $10 into the account 10,000 times. However, despite this predictability, the final balance isn’t consistent across executions. This inconsistency raises the question: Why does the final balance differ each time the code is run?</p><h3>A 101 on Race conditions.</h3><p>What you just saw can be explained by a race condition. Let’s first understand what a race condition is and then we will figure out how this can be resolved.</p><p>A race condition is a flaw that occurs in software when two or more operations must execute in the correct order, but the program has not been correctly synchronized to enforce this order. This results in unpredictable behavior, as the outcome depends on the non-deterministic ordering of actions (e.g., thread scheduling by the OS). Race conditions are often encountered in concurrent programming, where threads or goroutines access shared resources without proper synchronization mechanisms (like mutexes, channels, or atomic operations) to coordinate their access.</p><p>In Go, race conditions are commonly seen when multiple goroutines access and modify the same variable without using synchronization tools provided by the Go concurrency model. This can lead to several issues, including corrupted data or unpredictable behaviour.</p><p>The inconsistency in the final balance arises because the deposit operations by the Father and Mother cat are not atomic. The += operation consists of three steps: reading the current balance, adding $10 to this value, and writing the new value back to the balance. When these operations occur concurrently without proper synchronization, they can interfere with each other, leading to lost updates and a final balance that does not accurately reflect all the deposits.</p><h3>Introduction to mutexes</h3><p>A mutex, short for mutual exclusion, is a synchronization primitive used in Golang for concurrent programming. It ensures that only one goroutine (Golang’s lightweight thread) can access a shared resource at a time. This prevents race conditions, which occur when multiple goroutines try to modify the same data simultaneously, leading to unpredictable behaviour.</p><p>A mutex has two primary operations:</p><ul><li><strong>Lock</strong>: When a goroutine calls the Lock method on a mutex, it acquires the mutex. If the mutex is already locked by another goroutine, the calling goroutine is blocked until the mutex becomes available. This ensures that the critical section of code protected by the mutex can only be accessed by one goroutine at a time.</li><li><strong>Unlock</strong>: When a goroutine calls the Unlock method on a mutex, it releases the mutex, allowing other goroutines to acquire it and enter the critical section. It&#39;s crucial that a goroutine that has called Lock on a mutex calls Unlock once it is done with the shared resource to prevent deadlocks.</li></ul><h3>Solving the Race Condition</h3><p>To ensure that each deposit operation completes without interference from other concurrent operations, we can use a mutex. This will prevent the race condition by ensuring that each update to the balance is completed before another can begin.</p><p>Here’s how we can modify the code to include a mutex and solve the race condition:</p><pre>package main<br><br>import (<br>	&quot;fmt&quot;<br>	&quot;sync&quot;<br>)<br><br>type Bank struct {<br>	balance int<br>	mutex   sync.Mutex<br>}<br><br>func newAccount(amount int) *Bank {<br>	return &amp;Bank{balance: amount}<br>}<br><br>func (bank *Bank) depositAmount(amount int, name string, numberOfDeposits int, wg *sync.WaitGroup) {<br>	for i := 0; i &lt; numberOfDeposits; i++ {<br>		bank.mutex.Lock()<br>		bank.balance += amount<br>		bank.mutex.Unlock()<br>	}<br>	wg.Done()<br>}<br><br>func main() {<br>	bankAccount := newAccount(100)<br>	wg := sync.WaitGroup{}<br><br>	wg.Add(2)<br><br>	numberOfDeposits := 10000<br><br>	go bankAccount.depositAmount(10, &quot;Father Cat&quot;, numberOfDeposits, &amp;wg)<br>	go bankAccount.depositAmount(10, &quot;Mother Cat&quot;, numberOfDeposits, &amp;wg)<br><br>	wg.Wait()<br>	fmt.Printf(&quot;The current account balance is $%d.00\n&quot;, bankAccount.balance)<br>}</pre><p>In the modified code, we’ve added a mutex to the Bank struct. Inside the <strong>depositAmount</strong> method, we lock the mutex before updating the balance and unlock it immediately afterward. This ensures that when one goroutine is updating the balance, no other goroutine can enter the critical section until the mutex is unlocked. This effectively serializes access to the balance variable, ensuring that all deposits are accounted for correctly. When we run this code, The final balance is always the same. This happens because we mitigated the race condition using mutex locks.</p><p>By applying a mutex to synchronize access to shared resources in concurrent programming, we can prevent race conditions and ensure predictable and correct outcomes. In the case of our feline family, this means they can now reliably save for their kittens’ education, secure in the knowledge that every deposit made towards their future is accurately accounted for.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6d3a307d82a6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Unlocking the Mysteries: A Guide to Escape Analysis in Golang]]></title>
            <link>https://vaibhavjha.medium.com/unlocking-the-mysteries-a-guide-to-escape-analysis-in-golang-bdd77cecdc79?source=rss-a3b294fdba5b------2</link>
            <guid isPermaLink="false">https://medium.com/p/bdd77cecdc79</guid>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[memory-improvement]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[operating-systems]]></category>
            <category><![CDATA[concurrency]]></category>
            <dc:creator><![CDATA[Vaibhav Jha]]></dc:creator>
            <pubDate>Fri, 26 Apr 2024 06:11:26 GMT</pubDate>
            <atom:updated>2024-04-26T06:11:26.438Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mph9o9x5noVt59ufxCKn6A.jpeg" /></figure><p>Escape analysis is a technique used by the Go compiler to determine whether variables can be safely allocated on the function’s stack frame or if they must escape to the heap. This analysis plays a crucial role in Go’s memory management and performance characteristics, affecting how and where the memory for variables is allocated.</p><h3>The Basics</h3><p><strong>Stack Allocation:</strong> The memory allocated on the stack has its lifetime tied to the function’s execution. Once the function returns, the stack frame is unwound, and the memory used by these variables is automatically reclaimed. Stack allocation is fast and efficient because it avoids the overhead of garbage collection.</p><p><strong>Heap Allocation:</strong> Variables that escape to the heap do not have their scope tied to a particular function execution frame. They can be shared across different parts of the program and live longer. However, the heap allocation involves more overhead as they have to be garbage collected once they are no longer in use.</p><h3>How Escape Analysis Works</h3><p>The Go compiler performs escape analysis during the compilation phase. It examines the scope and usage of the variables to decide whether they can be allocated on the stack or if they need to be allocated on the heap. The main goal is to minimize heap allocation to optimize garbage collection pressure and improve performance.</p><p>A variable is determined to be escape to the heap if:</p><ul><li>It is returned from a function.</li><li>It is captured by a closure that outlives the function.</li><li>It is stored in a data structure that might outlive the function call.</li><li>It is passed by reference to other functions.</li></ul><h3>Benefits of Escape Analysis</h3><p><strong>Performance Optimization:</strong> By allocating objects on the stack where possible, Go can reduce the overhead associated with heap allocation and garbage collection, leading to faster and more efficient programs.</p><p><strong>Reduced Garbage Collection Pressure:</strong> Minimizing heap allocations reduces the amount of work the garbage collector needs to do, which can significantly improve the runtime performance, especially for memory-intensive applications.</p><p><strong>Automatic Memory Management:</strong> In languages like C or C++, Developers don’t need to explicitly manage the memory for stack-allocated variables, simplifying the development process while maintaining efficient memory usage.</p><h3>How to See Escape Analysis Results</h3><p>You can see the results of escape analysis in your Go programs by compiling your program with <strong>-gcflag ‘-m’ </strong>option. This command prints detailed information about the compiler’s decisions on variable allocation, including which variables escape to the heap and why.</p><p>Let’s compile the code below with <strong>-gcflag ‘-m’ </strong>and analyse the output.</p><pre>package main<br><br>func getAge() *int {<br>	age := 10<br>	return &amp;age<br>}<br><br>func main() {<br>	age := getAge()<br>	_ = *age<br>}</pre><pre>main.go:3:6: can inline getAge<br>main.go:8:6: can inline main<br>main.go:9:15: inlining call to getAge<br>main.go:4:2: moved to heap: age</pre><p>In this example, the <strong>age</strong> variable inside <strong>getAge</strong> function is allocated on the heap because <strong>getAge</strong> returns a pointer to age. The Go compiler&#39;s escape analysis detects that the memory address of <strong>age</strong> is being exposed outside the function through the return value. Since functions in Go can return and the callers can access their return values long after these functions have returned, the lifetime of <strong>age</strong> must be extended accordingly. The heap is used for such allocations because its memory is managed by the garbage collector, allowing <strong>age</strong> to outlive the <strong>getAge</strong> function&#39;s execution frame.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bdd77cecdc79" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Harnessing Counting Semaphores for Optimal Resource Management.]]></title>
            <link>https://vaibhavjha.medium.com/harnessing-counting-semaphores-for-optimal-resource-management-652f7fc79cf9?source=rss-a3b294fdba5b------2</link>
            <guid isPermaLink="false">https://medium.com/p/652f7fc79cf9</guid>
            <category><![CDATA[system-design-interview]]></category>
            <category><![CDATA[operating-systems]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[concurrency]]></category>
            <dc:creator><![CDATA[Vaibhav Jha]]></dc:creator>
            <pubDate>Fri, 26 Apr 2024 06:03:59 GMT</pubDate>
            <atom:updated>2024-04-26T06:03:59.765Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6rHYk2fKO3KeF221tmCY6A.jpeg" /></figure><p>Imagine we are hosting a website that changes images from one format to another. The Golang backend application responsible for managing the user requests internally calls the image converter service for conversion. The image converter service which is deployed on multi-core machine, can convert up to four images at once. However, converting images takes a lot of time, so we need to make sure we don’t overload the system with too many requests at the same time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/598/1*PlsYztVEcNdlzZOfJwtw8g.png" /></figure><p>To manage this, we need to throttle the number of requests we allow at once. If we treat each call to image conversion as a critical section can we use a simple lock (mutex) to manage access? Probably not. A standard mutex would only allow one request to be served at a time, which would slow things down a lot because our system can handle four image conversion requests at once.</p><p>Can we do better? As it turns out, yes. We can make use of a counting semaphore in this particular scenario. The counting semaphore will make sure that only a certain number of concurrent calls to image conversion service is allowed. Let’s first understand the concept of a counting semaphore and then I will show you how it can used for throttling in the current scenario.</p><h3>What is a counting semaphore?</h3><p>Working of a Semaphore:</p><ol><li><strong>Initialization</strong> — A counting semaphore is Initialized with a given permit size. The permit size defines the maximum number of threads that can access the critical section concurrently.</li><li><strong>Acquire Permit</strong> — Once a thread wants to enter the critical section, it needs to first acquire the permission from semaphore. This step reduces the permit by one. If the existing permit is already zero, thread waits for its turn.</li><li><strong>Release Permit</strong>- After a thread is done with the critical section, it increments the permit by one. Internally, a singal is sent to all the sleeping threads and one of them is chosen randomly for them to proceed.</li></ol><p>If you think about it, a counting semaphore is essentially a counter. Whenever a thread wants to execute in critical section, it first decrements the permit. If the permit is already zero, thread waits until the permit becomes non zero again. After the critical section work is complete, thread increments the permit. If other threads are waiting, one of them is allowed to proceed.</p><h3>Implementing Counting Semaphore using Condition Variable</h3><p>In Golang, the standard library does not include a counting semaphore, but it’s quite straightforward to implement one using a condition variable.</p><p>We have discussed the three main operations of a counting semaphore: Initialization, Acquire, and Release. Before we proceed with implementing these steps, let’s first define the structure that represents a counting semaphore.</p><pre>type CountingSemaphore struct {<br>	permits int       // defines the maximum number of permits<br>	cond *sync.Cond.  // Condition Variable<br>}</pre><p>Now that we’ve defined the CountingSemaphore structure, let’s go ahead and implement the three key steps.</p><p>Now that we’ve defined the CountingSemaphore structure, let’s go ahead and implement the three key steps.</p><p><strong>Step 1: Semaphore creation</strong></p><p>This step sets up the semaphore with a specified number of permits.</p><pre>func NewCountingSemaphore(permits int) *CountingSemaphore {<br>	return &amp;CountingSemaphore{permits: permits, cond: sync.NewCond(&amp;sync.Mutex{})}<br>}</pre><p><strong>Step 2: Acquiring the semaphore</strong></p><p>When Acquire is called, it reduces the permit count by one. If the permit count is already at zero, the goroutine that called Acquire will block.</p><pre>func (sema *CountingSemaphore) Acquire() {<br>	sema.cond.L.Lock()<br>	if sema.permits == 0 {<br>		sema.cond.Wait()<br>	}<br>	sema.permits--<br>	sema.cond.L.Unlock()<br>}</pre><p><strong>Step 3: Releasing the semaphore</strong></p><p>When Release is called, it increases the permit count by one. It also signals all the blocked Goroutines, allowing one of them, chosen at random, to continue execution.</p><pre>func (sema *CountingSemaphore) Release() {<br>	sema.cond.L.Lock()<br>	sema.permits += 1<br>	sema.cond.Signal()<br>	sema.cond.L.Unlock()<br>}</pre><p>That’s all there is to it. We’ve successfully created our own version of a counting semaphore using condition variable. Now, let’s revisit our original example to explore how counting semaphores can be used to throttle image conversion requests.</p><h3>Throttling the request to image conversion service</h3><p>We will use two mock method to mimic user Request handler and external image conversion service. The external service will mimic intensive processing by pausing for 3 seconds.</p><p>The main method will simulate user load by launching multiple user request handler goroutines simultaneously. Despite the presence of multiple concurrent user requests, the use of a semaphore will regulate access, ensuring that only a limited number of requests can invoke the image conversion service at any given time. In this example, we will limit this to four requests.</p><pre>package main<br><br>import (<br>	&quot;fmt&quot;<br>	&quot;sync&quot;<br>	&quot;time&quot;<br>)<br><br>type CountingSemaphore struct {<br>	size int<br>	cond *sync.Cond<br>}<br><br>func NewCountingSemaphore(size int) *CountingSemaphore {<br>	return &amp;CountingSemaphore{size: size, cond: sync.NewCond(&amp;sync.Mutex{})}<br>}<br><br>func (sema *CountingSemaphore) Acquire() {<br>	sema.cond.L.Lock()<br>	if sema.size == 0 {<br>		sema.cond.Wait()<br>	}<br>	sema.size--<br>	sema.cond.L.Unlock()<br>}<br><br>func (sema *CountingSemaphore) Release() {<br>	sema.cond.L.Lock()<br>	sema.size += 1<br>	sema.cond.Signal()<br>	sema.cond.L.Unlock()<br>}<br><br>func externalImageConversionService(userID int) {<br>	fmt.Println(&quot;Timestamp:&quot;, time.Now().Second(), &quot;&quot;, &quot;Converting image for user id &quot;, userID)<br>	time.Sleep(3 * time.Second)<br>}<br><br>func userRequestHandler(userID int, sema *CountingSemaphore, wg *sync.WaitGroup) {<br>	sema.Acquire()<br>	externalImageConversionService(userID)<br>	sema.Release()<br>	wg.Done()<br>}<br><br>func main() {<br>	sema := NewCountingSemaphore(4)<br>	wg := sync.WaitGroup{}<br>	for userId := range 10 {<br>		wg.Add(1)<br>		go userRequestHandler(userId, sema, &amp;wg)<br>	}<br><br>	wg.Wait()<br>}</pre><p>When we run the above code, it gives the following output.</p><pre>Timestamp: 52  Converting image for user id  1<br>Timestamp: 52  Converting image for user id  9<br>Timestamp: 52  Converting image for user id  0<br>Timestamp: 52  Converting image for user id  4<br><br>Timestamp: 55  Converting image for user id  5<br>Timestamp: 55  Converting image for user id  7<br>Timestamp: 55  Converting image for user id  8<br>Timestamp: 55  Converting image for user id  2<br><br>Timestamp: 59 Converting image for user id  3<br>Timestamp: 59 Converting image for user id  6</pre><p>As you can see, at any given moment, no more than four requests are made to the image conversion service. This occurs because the semaphore we implemented restricts access to the critical section to only four Goroutines at any time.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=652f7fc79cf9" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>