programming

How to Create Mutex and Its Use in Golang

Introduction of Sync.Mutex

Mutex or stands for Mutual Exclusion is a way to overcome race conditions in the Golang language. Mutex can be used to do locking and unlocking of a mutex so that if it is locked it will not be able to do locking again until we do unlocking.

So if we have a goroutine doing lock then the other goroutine will not be able to do lock until the goroutine does unlock, then the other goroutine can do lock. This is very suitable or usually a solution when there is a race condition problem faced when we are coding.

Still confused? Well later we will try further to this Mutex creation sample.

The Race Condition problem

We will try to create a simple code that makes the code have a Race Condition. You can see the code below.

func main() {
	var x int = 0
	for i := 0; i < 1000; i++ {
		go func() {
			x++
		}()
	}

	time.Sleep(500 * time.Microsecond)
	fmt.Println("counter : ", x)
}

So, we see that the above code if run will issue println with different counter values. Why is that? Because in the code there is a Race Condition where the x variable will simultaneously set and the last set is a different goroutine.

How to overcome Race Condition with sync.Mutex

Then how to avoid the Race Condition is one of them by using this Mutex. Let’s change the code above and then add it with the use of Mutex by looking at the additional code below.

func main() {
	var x int = 0
	var mu sync.Mutex
	for i := 0; i < 1000; i++ {
		go func() {
			mu.Lock()
			x++
			mu.Unlock()
		}()
	}

	time.Sleep(500 * time.Microsecond)
	fmt.Println("counter : ", x)
}

When we run the above code, each output will be fixed at 1000, so the count is correct and not different from before we used sync.Mutex.

So this is very useful if we are working on a count code that uses * goroutine* and setters into the same variable at the same time then we need to use sync.Mutex as locking and unlock so that the variable count is correct and reliable.

comments powered by Disqus