Skip to content

Instantly share code, notes, and snippets.

@refs
Created January 15, 2021 18:20
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 refs/fd5d23aef913fe456851689340e210da to your computer and use it in GitHub Desktop.
Save refs/fd5d23aef913fe456851689340e210da to your computer and use it in GitHub Desktop.
package mapConc
import (
"fmt"
"sync"
)
type db struct {
mutexes sync.Map
values sync.Map
}
// write stores a mutex...
func (d *db) writeMutex(k string, v *sync.RWMutex) {
d.mutexes.Store(k, v)
}
// write commit values to the values storage.
func (d *db) writeVal(k string, v string) {
d.values.Store(k, v)
}
// reads an actual value
func (d *db) readVal(k string) string {
read, ok := d.values.Load(k)
if !ok {
defer func() {
fmt.Printf("invalid read: %v: ", k)
d.values.Range(func(k, v interface{}) bool {
fmt.Printf("[k:%vv:%v]\t", k, v)
return true
})
}()
println()
return ""
}
return read.(string)
}
------------------------------------------------------------------------
package mapConc
import (
"strconv"
"sync"
"testing"
)
var _nRoutines = 5
func TestWrite(t *testing.T) {
out := make(chan struct{})
d := &db{
mutexes: sync.Map{},
values: sync.Map{},
}
for i := 0; i < _nRoutines; i++ {
d.writeMutex(strconv.Itoa(i), &sync.RWMutex{})
}
// writer goroutines
for i := 0; i < _nRoutines; i++ {
go func(ii int) {
nth, _ := d.mutexes.Load(strconv.Itoa(ii))
nth.(*sync.RWMutex).Lock()
d.writeVal(strconv.Itoa(ii), "test")
nth.(*sync.RWMutex).Unlock()
out <- struct{}{}
}(i)
}
//time.Sleep(1 * time.Second)
// reader goroutines
for i := 0; i < _nRoutines; i++ {
go func(ii int) {
nth, _ := d.mutexes.Load(strconv.Itoa(ii))
nth.(*sync.RWMutex).Lock()
d.readVal(strconv.Itoa(ii))
nth.(*sync.RWMutex).Unlock()
out <- struct{}{}
}(i)
}
for i := 0; i < _nRoutines * 2; i++ {
<- out
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment