Concurrency-safe types for Go. For now the module provides one type, SafeNumber, an integer protected by a mutex.
go get github.com/ralvarezdev/go-concurrencyThe package name is go_concurrency, so use an import alias.
import (
"fmt"
"sync"
goconcurrency "github.com/ralvarezdev/go-concurrency"
)
counter := goconcurrency.NewSafeNumber(0)
var wg sync.WaitGroup
for i := 0; i < 100; i++ {
wg.Add(1)
go func() {
defer wg.Done()
counter.Increment()
}()
}
wg.Wait()
fmt.Println(counter.GetValue()) // 100
counter.OperateValue(func(v int) int { return v * 2 })
counter.ResetValue() // back to the initial value (0)NewSafeNumber(initialValue int) *SafeNumber
Increment(),Decrement()— change the value by 1.IncrementAndGetValue(),DecrementAndGetValue()— change by 1 and return the new value.GetValue()— current value.OperateValue(fn),OperateAndGetValue(fn)— replace the value withfn(value), the latter also returning it.ResetValue()— restore the initial value.
All methods are safe on a nil receiver (they do nothing and return 0). The implementation is in safe_number.go; there are no tests.
GNU General Public License v3.0. See LICENSE.