Golang: multidimensional string array instead of maps -
in project need read value global variable using maps (global variable)
var url = make(map[string]string)
and error "concurrent writes"
assign value in function (cant assign global gives error non-declarative statement).
url["test"] = "http://google.com"
in php through multidimensioanl array , read value. there way use multidimensional array or maps in go assign , read in function?
any appreciated.
the concurrent writes
error happens when go runtime detects concurrent writes map different goroutines. feature added in go1.6:
the runtime has added lightweight, best-effort detection of concurrent misuse of maps. always, if 1 goroutine writing map, no other goroutine should reading or writing map concurrently. if runtime detects condition, prints diagnosis , crashes program. best way find out more problem run under race detector, more reliably identify race , give more detail.
you can initialize map on global level - see https://play.golang.org/p/ajqtqbgmem (or below) example. same code snippet shows how maps data races can prevented synchronisation mechanisms - use mutex, lock before writing map, , unlock afterwards.
package main import ( "fmt" "sync" ) var mu sync.mutex var mymap = map[string]string{"hello": "world", "foo": "bar"} func main() { demo() } func demo() { mu.lock() defer mu.unlock() mymap["hello"] = "gophers" fmt.println("hello, ", mymap["hello"]) }
another way avoid data race use channel of size 1 (non-buffered), similar tour example in https://tour.golang.org/concurrency/2: extract map channel, write it, , put channel.
https://golang.org/doc/articles/race_detector.html has more information data races , go race detector - useful tool identify hard-to-trace bugs in concurrent access.
Comments
Post a Comment