25% off

Use code FUNCMAIN at checkout for 25% off all premium courses.

Get started →

Mutexes in Go

June 24, 2021
Elliot Forbes

Elliot Forbes

Course Instructor

Hey Gophers! My name is Elliot and I'm the creator of TutorialEdge and I've been working with Go systems for roughly 5 years now.

In this video, we are going to be looking at Mutexes in Go and what they are used for.

Overview

package main

import (
	"fmt"
	"sync"
)

type Account struct {
	Balance int
	Mutex   *sync.Mutex
}

func (a *Account) Withdraw(value int, wg *sync.WaitGroup) {
	a.Mutex.Lock()
	a.Balance -= value
	a.Mutex.Unlock()
	wg.Done()
}

func (a *Account) Deposit(value int, wg *sync.WaitGroup) {
	a.Mutex.Lock()
	a.Balance += value
	a.Mutex.Unlock()
	wg.Done()
}

func main() {
	fmt.Println("Mutexes in Go")
	var m sync.Mutex

	account := Account{
		Balance: 1000,
		Mutex:   &m,
	}
	var wg sync.WaitGroup
	wg.Add(2)
	go account.Withdraw(700, &wg)
	go account.Deposit(500, &wg)
	wg.Wait()

	fmt.Println("Account Balances Updated")
	fmt.Println(account.Balance)
}

Output

$ go run main.go
Mutexes in Go
Account Balances Updated
800