Files
obitools4/pkg/obiutils/counter.go
Eric Coissac 67665a6b40 Xprize update
Former-commit-id: d38919a897961e4d40da3b844057c3fb94fdb6d7
2024-07-25 18:09:03 -04:00

43 lines
533 B
Go

package obiutils
import "sync"
type Counter struct {
Inc func() int
Dec func() int
Value func() int
}
func NewCounter(initial ...int) *Counter {
value := 0
lock := sync.Mutex{}
if len(initial) > 0 {
value = initial[0]
}
c := Counter{
Inc: func() int {
lock.Lock()
defer lock.Unlock()
value++
return value
},
Dec: func() int {
lock.Lock()
defer lock.Unlock()
value--
return value
},
Value: func() int {
lock.Lock()
defer lock.Unlock()
return value
},
}
return &c
}