Table of contents
1.
Introduction
2.
Go Mutex
3.
Examples
3.1.
Go Race Condition
3.2.
Go Mutex Implementation
4.
FAQs
5.
Key Takeaways
Last Updated: Mar 27, 2024

Go Mutex

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 race condition happens and how to solve them using mutexes in this blog post.

Go Mutex

A Go Mutex is a locking mechanism that ensures that only one Goroutine can access the important code section at any given moment. This is done in order to avoid racial tensions. The Mutex is included in the Sync package. A mutex has two methods defined.

  • Lock: Calling Lock function will “lock” the mutex. If any other goroutine calls Lock, it will block the thread until Unlock is called.
  • Unlock: Calling Unlock function will unlock the thread, and make it open for other processes.

 

Any code present between a call to Lock and Unlock will be executed by only one Goroutine.

mutex.Lock()

x = x + 1  // this statement be executed by only one Goroutine at any point of time 

mutex.Unlock()

 

If one Goroutine already holds the lock and another is attempting to obtain it, the new Goroutine will be halted until the mutex is unlocked. To grasp this concept, first, grasp the concept of a programme with race conditions.

Examples

Now, let us go through the example program where race conditions exist. And we will try to solve this problem using the mutexes in Go. You can learn more about Go Race here.

Go Race Condition

Here is an example of a program that encounters race conditions.

// Program with race condition
package main

import (
  "fmt"
  "sync"
)

var CodingNinjas = 0

// This is the function we’ll run in every
// goroutine.
func worker(wg *sync.WaitGroup) {
  CodingNinjas = CodingNinjas + 1
  wg.Done()
}
func main() {
  var w sync.WaitGroup
  for i := 0; i < 1000; i++ {
    w.Add(1)
    go worker(&w)
  }
  w.Wait()
  fmt.Println("Value of x", CodingNinjas)
}

The worker function in the programme above increases the value of CodingNinjas by one and then calls Done() on the WaitGroup to notify it of its completion. 1000 times the worker function is called. 

Each of these Goroutines runs at the same time, resulting in a race condition while trying to increase CodingNinjas since several Goroutines are attempting to access the value of CodingNinjas at the same time. Because of the race condition, running the same programme numerous times produces different results each time.

Output

Go Mutex Implementation

Here is an example of a program which how race condition is fixed.

// Program with race condition example fixed by mutex
package main

import (
  "fmt"
  "sync"
)

var CodingNinjas = 0

func worker(wg *sync.WaitGroup, m *sync.Mutex) {
  m.Lock()
  CodingNinjas = CodingNinjas + 1
  m.Unlock()
  wg.Done()
}
func main() {
  var w sync.WaitGroup
  var m sync.Mutex
  for i := 0; i < 1000; i++ {
    w.Add(1)
    go worker(&w, &m)
  }
  w.Wait()
  fmt.Println("Value of x", CodingNinjas)
}

Output

Mutex is a struct type, and a Mutex variable ‘m’ is created. The code that increments CodingNinjas between m.Lock() and m.Unlock() is altered in the worker function (). This piece of code can now only be executed by one Goroutine at a time, which eliminates the race issue.

The mutex's address must be given to the function. If the mutex is instead passed by value, each Goroutine will have its own copy of the mutex, and the race condition will still exist.

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 utilised 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 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 concept of mutex in the Go programming language. We also demonstrated the Go race conditions using examples. We also learned how to solve the race conditions using the Go mutexes. We learned the implementation of Go mutexes.

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

For more information, refer to Go. More Go concepts are Go DirectoriesGo Introduction.

Refer to our guided paths on Coding Ninjas Studio to learn more about DSA, Competitive Programming, JavaScript, System Design, etc. Enroll 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