Skip to content

Instantly share code, notes, and snippets.

@JustAdam
Created November 4, 2014 20:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JustAdam/bc3e450d6682a88403a8 to your computer and use it in GitHub Desktop.
Save JustAdam/bc3e450d6682a88403a8 to your computer and use it in GitHub Desktop.
Go: Read/Write variable locking - demo of Read locking without block with slow Write lock
package main
import (
"fmt"
"sync"
"time"
)
type C struct {
sync.RWMutex
i int
files []string
}
type A struct {
sync.Mutex
c *C
}
func (c *C) Init() {
c.Lock()
c.files = make([]string, 0)
for i := c.i; i < c.i+5; i++ {
c.files = append(c.files, fmt.Sprintf("file%d", i))
time.Sleep(time.Microsecond * 500)
}
c.i += 5
c.Unlock()
}
func (c *C) GetFiles() []string {
c.RLock()
defer c.RUnlock()
return c.files
}
func (a *A) loadConfiguration() {
c := *a.c
c.Init()
a.Lock()
a.c = &c
a.Unlock()
}
func main() {
app := &A{
c: &C{},
}
app.loadConfiguration()
go func() {
ticker := time.NewTicker(time.Second * 5)
for {
select {
case <-ticker.C:
app.loadConfiguration()
}
}
}()
wait := make(chan bool, 1)
go func() {
ticker := time.NewTicker(time.Second * 1)
for {
select {
case <-ticker.C:
fmt.Println("app.c.GetFiles>>", app.c.GetFiles())
}
}
}()
go func() {
ticker := time.NewTicker(time.Second * 1)
for {
select {
case <-ticker.C:
fmt.Println("app.c.files>>", app.c.files)
}
}
}()
<-wait
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment