add go mutext
parent
14c2afd04d
commit
35f86b8c87
|
@ -1,6 +1,6 @@
|
||||||
# [strings](https://golang.org/pkg/strings/)
|
# [strings](https://golang.org/pkg/strings/)
|
||||||
|
|
||||||
Replace list of strings by using Replacer:
|
Replace list of strings by using `Replacer`:
|
||||||
|
|
||||||
```go
|
```go
|
||||||
template := "My city is {city} and my country is {country}"
|
template := "My city is {city} and my country is {country}"
|
||||||
|
|
|
@ -0,0 +1,43 @@
|
||||||
|
# [sync](https://golang.org/pkg/sync/)
|
||||||
|
|
||||||
|
Use `Mutext` to prevent accessing variable from different goroutine at the same time:
|
||||||
|
|
||||||
|
```go
|
||||||
|
type foo struct {
|
||||||
|
mu sync.Mutext
|
||||||
|
|
||||||
|
bar map[string]string
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f *foo) doSomething {
|
||||||
|
f.mu.Lock()
|
||||||
|
defer f.mu.Unlock()
|
||||||
|
|
||||||
|
// do the thing
|
||||||
|
}
|
||||||
|
|
||||||
|
```
|
||||||
|
|
||||||
|
Use `RWMutex` if there are many readers, and few writers:
|
||||||
|
|
||||||
|
```go
|
||||||
|
type foo struct {
|
||||||
|
mu sync.RWMutext
|
||||||
|
|
||||||
|
bar map[string]string
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f *foo) read {
|
||||||
|
f.mu.RLock()
|
||||||
|
defer f.mu.RUnlock()
|
||||||
|
|
||||||
|
// read
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f *foo) write {
|
||||||
|
f.mu.Lock()
|
||||||
|
defer f.mu.Unlock()
|
||||||
|
|
||||||
|
// write
|
||||||
|
}
|
||||||
|
```
|
Loading…
Reference in New Issue