Created
November 4, 2014 18:53
-
-
Save JustAdam/1ee9655625591d503bdc to your computer and use it in GitHub Desktop.
Go: Read/Write variable locking - demo showing the problem when accessing the variable directly and via a read lock when a slow write lock is running
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" | |
) | |
type C struct { | |
sync.RWMutex | |
i int | |
files []string | |
} | |
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.Millisecond * 500) | |
} | |
c.i += 5 | |
c.Unlock() | |
} | |
func (c *C) GetFiles() []string { | |
c.RLock() | |
defer c.RUnlock() | |
return c.files | |
} | |
func main() { | |
c := &C{} | |
c.Init() | |
go func() { | |
ticker := time.NewTicker(time.Second * 5) | |
for { | |
select { | |
case <-ticker.C: | |
c.Init() | |
} | |
} | |
}() | |
wait := make(chan bool, 1) | |
go func() { | |
ticker := time.NewTicker(time.Second * 1) | |
for { | |
select { | |
case <-ticker.C: | |
fmt.Println("c.GetFiles>>", c.GetFiles()) | |
} | |
} | |
}() | |
go func() { | |
ticker := time.NewTicker(time.Second * 1) | |
for { | |
select { | |
case <-ticker.C: | |
fmt.Println("c.files>>", c.files) | |
} | |
} | |
}() | |
<-wait | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment