ruk·si

🐹 Go
Embedded Lock

Updated at 2022-01-20 14:20

You can include sync.Mutex to variables using struct embedding to make them thread safe.

package main

import (
    "runtime"
    "sync"
)

var count struct {
    sync.Mutex
    value int64
}

func assert(condition bool) {
    if !condition {
        panic("assert failed")
    }
}

func main() {
    go func() {
        count.Lock()
        defer count.Unlock()
        count.value++
    }()
    assert(count.value == 0)
    runtime.Gosched() // allow goroutines to run
    count.Lock()      // blocks for a tiny amount so value gets changed
    defer count.Unlock()
    assert(count.value == 1)
}

Source