2016-02-16 11:17 阅读 69

在Go中使用映射时忽略goroutine /线程安全的危险是什么?

Go's map is said not to be goroutine-safe (see here and here). I'm interested at finding out what could happen in a case where I neglect to protect access to the map using mutex/etc.

Specifically, can any of the following happen?

  1. Assuming I have a map with keys k1, k2, ..., kn, can a concurrency issue lead to getting map[ki] when I asked for map[kj] (i != j)?
  2. Can it lead to a panic in the application?
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享

1条回答 默认 最新

  • 已采纳
    dongsu1539 dongsu1539 2016-02-16 14:51

    As the comments have already stated, races are bad. Go has very weak guarantees, unlike Java, and hence a program that has any race is allowed to have undefined behavior even when the race-containing code is not executed. In C, this is called "catch-fire semantics". The presence of a race means any outcome is possible, to include your computer catching on fire.

    However, in Go it is easy to make a map thread-safe. Consider the following:

    // Global variable defining a map
    var safemap = struct {
        m map[string]string
    }{m: make(map[string]string)}

    You can do safe reads from the map like this:

    // Get a read lock, then read from the map
    defer safemap.RUnlock()
    return safemap.m[mykey] == myval

    And you can do safe modifications like this:

    // Delete from the map
    delete(safemap.m, mykey)

    or this:

    // Insert into the map
    safemap.m[mykey] = myval
    点赞 评论 复制链接分享