~/Overview of Golang sync Package

Feb 2, 2024


The sync package in Golang provides primitives for concurrency including mutual exclusion, wait groups, and once-only execution.

Mutex provides a lightweight lock for sharing data safely between goroutines.

Example of Mutex

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
import (
    "sync"
)

var mu sync.Mutex
var count int

func increment() {
    mu.Lock()
    count++
    mu.Unlock()
}

WaitGroup allows waiting for a set of goroutines to finish.

Example of WaitGroup

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
import (
    "sync"
)

var wg sync.WaitGroup

for i := 0; i < 3; i++ {
    wg.Add(1)
    go func() {
        // work
        wg.Done()
    }()
}
wg.Wait()

Once executes a function only one time regardless of how many goroutines invoke it.

Example of Once

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
import "sync"

var once sync.Once

func setup() {
    // Initialize only once
}

func main() {
    once.Do(setup)
}

The sync package also includes RWMutex, Cond, and Pool for advanced use cases. For more, consult the Go sync documentation.

Tags: [golang] [concurrency]