Understanding Golang’s “Do not communicate by sharing memory; instead, share memory by communicating”
<p>Golang (Go) is renowned for its straightforward and effective approach to concurrent programming. One of its guiding philosophies is the phrase: “Do not communicate by sharing memory; instead, share memory by communicating.” To truly understand the essence of this philosophy, let’s explore it using Golang examples that illustrate it.</p>
<h1>Traditional Approach in Go: Mutex Locks and Shared Memory</h1>
<p>Even though Go provides modern concurrency primitives like channels, it still allows for the use of mutex locks for those who prefer a more traditional approach to concurrency. Below the diagram of the sample code that we present right after it.</p>
<p><img alt="" src="https://miro.medium.com/v2/resize:fit:700/1*Bba7kmbCUHNm5Y6lLhORyg.png" style="height:220px; width:700px" /></p>
<h1>Example: Summing Numbers Concurrently</h1>
<p>Let’s consider a simple task: summing an array of numbers. We can divide this task among multiple Goroutines and have each one sum part of the array. We could use a shared variable to accumulate the total sum, making sure to lock it before each update.</p>
<p><a href="https://blog.stackademic.com/understanding-golangs-do-not-communicate-by-sharing-memory-instead-share-memory-by-747e84998e9"><strong>Visit Now</strong></a></p>