Skip to content

Latest commit

 

History

5 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 

Repository files navigation

go-concurrency

Concurrency-safe types for Go. For now the module provides one type, SafeNumber, an integer protected by a mutex.

Installation

go get github.com/ralvarezdev/go-concurrency

The package name is go_concurrency, so use an import alias.

Usage

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)

API

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 with fn(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.

License

GNU General Public License v3.0. See LICENSE.

Releases

Packages

Used by

Contributors

Languages