Created
November 4, 2014 20:18
-
-
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
This file contains 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" | |
) | |
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