What is Mutex in Golang?

Learn via video courses
Topics Covered

Overview

Mutex is a programming concept used to provide synchronization in concurrent programs. To avoid conflicts, Mutex in Golang ensures that no two goroutines can access a variable at a given time.

In this article, we will learn and implement examples of mutual exclusion.

Introduction to Mutex in Golang

Golang provides us with a very powerful tool like Goroutines that is used to do multi-Threading. When Two or more Goroutines are dealing with the same variable in a program, which is manipulated frequently, It causes a condition called "Racing". Racing happens when two or more Goroutines try to update the value of a shared resource. As this updation causes the value to be some random value making our application behavior undesirable.   To avoid such issues to happen, we can use locks. Mutex in Golang is used to do locking. This is available as a standard package called "sync". A Mutex locks a shared resource and releases the lock once the updation of the shared resource is completed. This avoids the race condition.

Using a Mutex to Lock Data

Below is an example showing the use of Mutex in Golang, where we try to manipulate a common parameter and print it.

Output:

Try on playground

Reader/Writer Mutex

An RWMutex is a reader/writer mutual exclusion lock. In some conditions we might need locks only for writes and data reading can be done concurrently. In this scenario, we can use RWMutex.

The below example shows the use of RWMutex.

Output:

Try on playground

Adding Mutexes into Structs

It's good practice to keep the mutex close to the field that it wants to protect. If the main purpose of the mutex is to protect fields in the struct. It's very convenient to add the mutex as a field of that struct which naturally protects the fields from concurrent access.   The below Example demonstrates the use of mutexes instructs.

Common Pitfalls

Mutexes in Golang provides a great way to handle race condition. But with great power comes great responsibilities and implementing mutexes badly can cause conditions like starvation.    When locking shared resources we can miss unlocking it or keep the lock for an extended time. We must explicitly use the lock for required things only. using defer statements is an excellent option and even better is to have the unlocking as per requirements.

Conclusion

  • Understood the concept of Mutex in Golang.
  • Learned the use cases for Mutexes.
  • Implemented examples for Mutex in Golang.