Go by Example: Mutexes

A mutex is a synchronization mechanism that controls access to a shared resource in a concurrent environment. In Go, the sync package provides a Mutex type that can be used to implement mutual exclusion, ensuring that only one Goroutine can access a shared resource at any given time.

Here’s an example of using a Mutex in Go:

package main

import (

var counter int
var mutex sync.Mutex

func incrementCounter(wg *sync.WaitGroup) {
	defer wg.Done()

	for i := 0; i < 1000; i++ {

func main() {
	var wg sync.WaitGroup

	for i := 0; i < 100; i++ {
		go incrementCounter(&wg)

	fmt.Println("Final Counter Value:", counter)

In this example, a global variable counter is declared and a Mutex named mutex is used to control access to it. A Goroutine incrementCounter increments the value of the counter 1000 times. The Goroutine acquires the lock using the mutex.Lock method before accessing the counter and releases the lock using the mutex.Unlock method after the increment operation is complete. The use of a Mutex ensures that only one Goroutine can access the counter at any given time, preventing race conditions and ensuring the integrity of the shared resource.


Leave a Reply

Your email address will not be published. Required fields are marked *