A Mutex is a synchronization technique used as a locking mechanism to ensure that only one Goroutine is accessing a particular section of code which is prone for race condion at any point of time. This is done to prevent race conditions from happening. Sync package of Golang contains the Mutex. Two methods of Mutex are used to synchronize the program: 

i. Lock()

ii. Unlock()

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

    Suppose we have a variable like this:

var count = 0;

Now, if we want to increase it value by 1 through multiple goroutines then, race condition may appear. Because increment operation (like, count = count + 1) is comprised of three atomic operations.

1. Reading the original value.

2. Increase its value by 1.

3. Reassign its value.

So, when multiple goroutines will try to perform the increment operation (count = count + 1), result of some goroutine will get mutated.

    To avoid such type of race condition, we need to use some kind of synchronization technique. Mutex is one of them. In golang, we use mutex like below program:


package main

import (
"fmt"
"time"
"sync"
)

var count = 0
var mutex sync.Mutex

func incrementValue() {
for i := 0; i < 10000; i++ {
mutex.Lock()
count = count + 1
mutex.Unlock()
}
}
func main() {
go incrementValue()
go incrementValue()
time.Sleep(time.Second * 1)
fmt.Println(count)
}

    Result of above program: 20000