Created
January 15, 2021 18:20
-
-
Save refs/fd5d23aef913fe456851689340e210da to your computer and use it in GitHub Desktop.
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 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