doudu5498 2018-07-12 08:58
浏览 259
已采纳

golang struct在没有锁定的情况下并发读写也可以运行吗?

concurrentMap() function Have WARNING: DATA RACE, And fatal error: concurrent map read and map write

concurrentStruct() have WARNING: DATA RACE, But running ok

why the struct can DATA RACE?

package main

import (
"sync"
)

func main() {
// concurrentMap()
concurrentStruct()
// concurrentStructWithMuLock()
}

type Metadata struct {
mu sync.RWMutex //

  • 写回答

1条回答 默认 最新

  • dscdttg4389 2018-07-12 09:11
    关注

    Unsynchronized, concurrent access to any variable from multiple goroutines where at least one of them is a write is undefined behavior. Do not try to find logic in undefined behavior, just use proper synchronization. Undefined means it may run "correctly" or it may run "incorrectly" (giving incorrect results), or it may crash or anything else. That's what undefined means. Read more about it here: Is it safe to read a function pointer concurrently without a lock?

    Your concurrentStructWithMuLock() has actually no data race, because you are using a mutex to properly synchronize access to the struct.

    And with concurrentMap() that's another issue. Go 1.6 added a lightweight concurrent misuse of maps detection to the runtime:

    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 the program under the race detector, which will more reliably identify the race and give more detail.

    So this is an intentional crash by the runtime, because it detects unsynchronized access to the map. This is a "feature" of the Go runtime, and it crashes your app because no data race should be left in your app (to prevent undefined behavior). Read more about it here: How to recover from concurrent map writes?

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 微信会员卡等级和折扣规则
  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分