dongyuying1507 2016-07-25 14:17
浏览 61

Golang:多维字符串数组而不是地图

In my project I need to read a value as a global variable so I am using maps (global variable)

var url = make(map[string]string)

and I occasionally get into error "Concurrent writes" as I assign value in a function (cant assign global as it gives an error non-declarative statement).

url["test"] = "http://google.com"

In PHP I could easily do this through an multidimensioanl array and read the value. Is there a way I could just use multidimensional array or maps in Go to just assign and read it in a function?

Any help is appreciated.

  • 写回答

1条回答 默认 最新

  • doubi1931 2016-07-25 21:17
    关注

    The Concurrent writes error happens when the Go runtime detects concurrent writes to the map by different goroutines. It is a feature added in go1.6:

    https://blog.golang.org/go1.6

    The runtime has added lightweight, best-effort detection of concurrent misuse of maps. As always, if one goroutine is writing to a map, no other goroutine should be reading or writing the map concurrently. If the runtime detects this condition, it prints a diagnosis and crashes the program. The best way to find out more about the problem is to run it under the race detector, which will more reliably identify the race and give more detail.

    You can initialize a map on a global level - see https://play.golang.org/p/AjqtQBGMEM (or below) for an example. The same code snippet shows how maps data races can be prevented with synchronisation mechanisms - use a mutex, lock before writing to a map, and 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 to avoid the data race is to use a channel of size 1 (non-buffered), similar to the Tour example in https://tour.golang.org/concurrency/2: extract the map from the channel, write to it, and put it back to the channel.

    https://golang.org/doc/articles/race_detector.html has more information about data races and the Go race detector - a very useful tool to identify hard-to-trace bugs in concurrent access.

    评论

报告相同问题?

悬赏问题

  • ¥15 矩阵加法的规则是两个矩阵中对应位置的数的绝对值进行加和
  • ¥15 活动选择题。最多可以参加几个项目?
  • ¥15 飞机曲面部件如机翼,壁板等具体的孔位模型
  • ¥15 vs2019中数据导出问题
  • ¥20 云服务Linux系统TCP-MSS值修改?
  • ¥20 关于#单片机#的问题:项目:使用模拟iic与ov2640通讯环境:F407问题:读取的ID号总是0xff,自己调了调发现在读从机数据时,SDA线上并未有信号变化(语言-c语言)
  • ¥20 怎么在stm32门禁成品上增加查询记录功能
  • ¥15 Source insight编写代码后使用CCS5.2版本import之后,代码跳到注释行里面
  • ¥50 NT4.0系统 STOP:0X0000007B
  • ¥15 想问一下stata17中这段代码哪里有问题呀