Skip to content

Instantly share code, notes, and snippets.

@xeoncross
Last active August 2, 2021 22:58
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xeoncross/1acefb134973e3abe590 to your computer and use it in GitHub Desktop.
Save xeoncross/1acefb134973e3abe590 to your computer and use it in GitHub Desktop.
Singleton global counter map for safely keeping track of numbers by name (for debugging metrics) http://play.golang.org/p/9bDMDLFBAY
package main
import (
"fmt"
"sync"
)
// https://blog.golang.org/go-maps-in-action#TOC_6.
// http://stackoverflow.com/questions/1823286/singleton-in-go
type single struct {
mu sync.Mutex
values map[string]int64
}
var counters = single{
values: make(map[string]int64),
}
func (s *single) Get(key string) int64 {
s.mu.Lock()
defer s.mu.Unlock()
return s.values[key]
}
func (s *single) Incr(key string) int64 {
s.mu.Lock()
defer s.mu.Unlock()
s.values[key]++
return s.values[key]
}
func main() {
fmt.Println(counters.Incr("bar"))
fmt.Println(counters.Incr("bar"))
fmt.Println(counters.Incr("bar"))
fmt.Println(counters.Get("foo"))
fmt.Println(counters.Get("bar"))
}
package counters
import "sync"
// https://blog.golang.org/go-maps-in-action#TOC_6.
// http://stackoverflow.com/questions/1823286/singleton-in-go
type single struct {
mu sync.Mutex
values map[string]int64
}
// Global counters object
var counters = single{
values: make(map[string]int64),
}
// Safely get the value of the given counter
func Get(key string) int64 {
counters.mu.Lock()
defer counters.mu.Unlock()
return counters.values[key]
}
// Safely increase the value of the given counter
func Incr(key string) int64 {
counters.mu.Lock()
defer counters.mu.Unlock()
counters.values[key]++
return counters.values[key]
}
// All the counters
func All() map[string]int64 {
counters.mu.Lock()
defer counters.mu.Unlock()
return counters.values
}
package main
import "sync"
// Sync map (not used in the other files)
// SyncMap for concurrent use
type SyncMap struct {
mu sync.Mutex
values map[int64]interface{}
}
// NewSyncMap object
func NewSyncMap() (sm SyncMap) {
sm.values = make(map[int64]interface{})
return
}
// Exists checks for value existing
func (s *SyncMap) Exists(key int64) bool {
s.mu.Lock()
defer s.mu.Unlock()
_, e := s.values[key]
return e
}
// Get a key (if exists)
func (s *SyncMap) Get(key int64) interface{} {
s.mu.Lock()
defer s.mu.Unlock()
return s.values[key]
}
// Set a key
func (s *SyncMap) Set(key int64, v interface{}) {
s.mu.Lock()
defer s.mu.Unlock()
s.values[key] = v
}
// All keys and their value
func (s *SyncMap) All(key int64) (m map[int64]interface{}) {
s.mu.Lock()
defer s.mu.Unlock()
for i, v := range s.values {
m[i] = v
}
return m
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment