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 stm32代码移植没反应
  • ¥15 matlab基于pde算法图像修复,为什么只能对示例图像有效
  • ¥100 连续两帧图像高速减法
  • ¥15 组策略中的计算机配置策略无法下发
  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)
  • ¥50 mac mini外接显示器 画质字体模糊