Table of contents
1.
Introduction
2.
Go Race Conditions
3.
Examples
4.
FAQs
5.
Key Takeaways
Last Updated: Mar 27, 2024
Easy

Go Race Condition in Golang

Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Go, often known as Golang, is a Google-developed open-source, compiled, and statically typed computer language. It's designed to be simple, fast, readable, and efficient.

Multi-threaded application development is a difficult task that necessitates careful design before implementation. Understanding the fundamentals is critical if you're using a single-threaded language like JavaScript. The fundamentals are similar whether you are familiar with low-level languages like C or C++. We'd like to describe how go race condition happens in this blog post.

Go Race Conditions

When numerous threads attempt to access and modify the same data, a go race condition occurs (memory address). For example, if one thread tries to raise an integer while another tries to read it, a race scenario will occur. If the variable is read-only, however, there will be no race condition. When Goroutines are utilised in Golang, threads are created implicitly.

Consider the given example to gain a better understanding of concurrency. Consider a basket filled with apples and two people standing nearby. One is given the responsibility of counting, weighing, and examining other key characteristics of each and every apple in the basket.

As soon as he starts observing the apples in order to draw some conclusions, the second person tampers some apple forms, beats them until they're powdered, and even consumes some apple fragments. It's happening at the same time: one is noting the characteristics of apples, while the other is destroying the original characteristics. The first one has no way of knowing the original data because he is only taking note of the modified data, which he is oblivious of. This is a competitive situation. Both operations running at the same time interact with various common things, resulting in significant data loss.

Examples

Let's try to create a go race condition. The simplest way to do it is by using multiple goroutines, and at least one of the goroutines must be written to a shared variable.

The following code demonstrates a simple way to create a go race condition.

  • A goroutine.
  • Another goroutine writes to the same variable by increasing its value.

 

Let's code and understand go race conditions practically!

package main

import (
  "fmt"
  "time"
)

func execute(codingninjas string) {
  for i := 1; true; i++ {
    fmt.Println(codingninjas, i)
    time.Sleep(time.Millisecond * 100)
  }
}

func main() {
  execute("First Statement ")
  execute("Second Statement ")
  fmt.Println("program ends successfully")
}

 

Output

If you're using Windows, you're likely to see something similar on your screen. Unless you actively stop it or it runs out of system memory for execution, the aforementioned output will continue indefinitely.

Let us have a look at a different scenario.

package main
import (
  "fmt"
  "time"
)
func execute(codingninjas string) {
  for i := 1; true; i++ {
      fmt.Println(codingninjas, i)
      time.Sleep(time.Millisecond * 100)
  }
}
func main() {
  // Simple and concurrent go program
  go execute("First Statement ")
  execute("Second Statement ")
  fmt.Println("program ends successfully")
}

 

Output

If you're using Windows, you're likely to see something similar on your screen. Let's explore what happens if you create two goroutines in the same programme. When you establish a goroutine in Go, it usually speeds up the execution by delegating the waiting time to other tasks.

package main
 import (
   "fmt"
   "time"
)
 func execute(some string) {
   for i := 1; true; i++ {
       fmt.Println(some, i)
       time.Sleep(time.Millisecond * 100)
   }
}
 func main() {
   // Simple go program with concurrency
   go execute("First")
   go execute("Second")
   fmt.Println("Program ends successfully")
}

 

Output

If you're using Windows, you're likely to see something similar on your screen. To wrap up our discussion, consider the following go race condition scenario:

package main
 // one goroutine is the default goroutine 
import (
   "fmt"
   "runtime"
   "sync"
)
 var wgIns sync.WaitGroup
 func main() {
   counter := 0
   wgIns.Add(50)
   for i := 0; i < 50; i++ {
       go func() {
           for j := 0; j < 50; j++ {
               counter += 1
           }
           wgIns.Done()
       }()
   }
   fmt.Println("The number of goroutines before wait = ", runtime.NumGoroutine())
   wgIns.Wait()
   fmt.Println("Counter value = ", counter)
   fmt.Println("The number of goroutines after wait = ", runtime.NumGoroutine())
}

 

Output

The count of the number of goroutines before and after the wait is inconsistent. This  inconsistency is caused by racial factors. In basic terms, imagine that you have one candy and two children rush up to you, claiming that they are both hungry. They end up battling over that one chocolate bar, and they sprint to acquire it. This is a competitive situation. The solution is to get another candy so that both of them can eat candy in peace. Similarly, we can increase resource allocation to prevent go race conditions from arising.

FAQs

1. What is Go?

Go, often known as Golang, is a Google-developed open-source, compiled, and statically typed computer language. It's designed to be simple, fast, readable, and efficient.

2. What is a race condition?

A race condition occurs when multiple threads try to access and modify the same data.

3. Is Google using Go internally?

Yes. Within Google, Go is widely utilized in production. The server that powers golang.org is a good example. It's just the godoc document server operating on Google App Engine in a production environment. Google's download service, dl.google.com, which serves Chrome binaries and other huge installable like apt-get packages, is a more notable example.

4. What other companies use Go?

Go is becoming more popular around the world, particularly in the cloud computing arena, but not entirely. Docker and Kubernetes are two significant Go-based cloud infrastructure projects, although there are many others. But it isn't only a cloud. But it's not simply a cloud. The Go Wiki has a page that lists some of the numerous companies that use Go, which is updated on a regular basis.

5. What IDEs(Integrated Development Environments) does Go support?

The Go project does not include a custom IDE, but the language and libraries have been designed to make it easy to analyze source code. As a consequence, most well-known editors and IDEs support Go well, either directly or through a plugin.

The list of well-known IDEs and editors that have good Go support available includes Emacs, Vim, VSCode, Atom, Eclipse, Sublime, IntelliJ (through a custom variant called Goland), and many more. Chances are, your favourite environment is a productive one for programming in Go.

Key Takeaways

In this article, we learned about the go race conditions in the Go programming language. We also demonstrated the Go race conditions using examples. We precisely understood the concept of the Go race conditions.

Apart from this, you can also expand your knowledge by referring to more articles on Go.

For more information, refer to Go.

Refer to our guided paths on Coding Ninjas Studio to learn more about DSA, Competitive Programming, JavaScript, System Design, etc. Enrol in our courses and refer to the mock test and problems available; take a look at the interview experiences and interview bundle for placement preparations.

Do upvote our blog to help other ninjas grow.

Happy Learning!
 

Live masterclass