Last active
October 29, 2018 15:57
-
-
Save devries/4b05f104e2e69a9ac26a1ad2e6b0193e to your computer and use it in GitHub Desktop.
Singleton Example for Go
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"sync" | |
"time" | |
) | |
func main() { | |
go setter() | |
s := Singleton() | |
for i := 0; i < 30; i++ { | |
v := s.Get() | |
fmt.Printf("%d: %d\n", i, v) | |
time.Sleep(time.Duration(1) * time.Second) | |
} | |
} | |
func setter() { | |
s := Singleton() | |
for i := 0; i < 10; i++ { | |
s.Set(i) | |
time.Sleep(time.Duration(2) * time.Second) | |
} | |
} | |
type singleton struct { | |
i int | |
mu sync.RWMutex | |
} | |
var ( | |
globalS *singleton | |
once sync.Once | |
) | |
func (s *singleton) Get() int { | |
s.mu.RLock() | |
defer s.mu.RUnlock() | |
return s.i | |
} | |
func (s *singleton) Set(v int) { | |
s.mu.Lock() | |
defer s.mu.Unlock() | |
s.i = v | |
} | |
func Singleton() *singleton { | |
once.Do(func() { | |
globalS = &singleton{} | |
}) | |
return globalS | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
On go play: https://play.golang.org/p/Yg1ee5VZTkM