dongruo0909 2016-02-16 11:17
浏览 83
已采纳

在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 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 {
        sync.RWMutex
        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
    safemap.RLock()
    defer safemap.RUnlock()
    return safemap.m[mykey] == myval
    

    And you can do safe modifications like this:

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

    or this:

    // Insert into the map
    safemap.Lock()
    safemap.m[mykey] = myval
    safemap.Unlock()
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog