普通网友 2016-08-15 06:28
浏览 70
已采纳

通过并发访问此线程安全吗?

I have struct with count property need to thread-safe access.

I know it can be done with sync.Mutex or sync.RWMutex. But I am not sure it's ok like this:

type Status struct {
    count uint32

    attr1 string
    attr2 string
}

func (s *Status) Get() uint32 {
    return atomic.LoadUint32(&s.count)
}

func (s *Status) Add(n uint32) {
    atomic.AddUint32(&s.count, n)
}

func (s *Status) Reset(n uint32) {
    atomic.StoreUint32(&s.count, n)
}

Thank you.

Edit:

I'm confused that access field directly s.count is not safe. But atomic.LoadUint32(&s.count) is safe?

  • 写回答

1条回答 默认 最新

  • drqrdkfue521903877 2016-08-15 06:50
    关注

    Yes, if only those 3 methods access the count field, your solution is safe to use concurrently from multiple goroutines.

    But know that the value returned by Status.Get() may be "outdated" by the time you attempt to use it. E.g.:

    s := &Status{}
    
    if s.Get() == 3 {
        fmt.Println(s.Get()) // This may or may not print 3
    }
    
    // Or
    c := s.Get()
    fmt.Println(c == s.Get()) // This may or may not print true
    

    The above example may or may not print 3 and true as the 2nd call to s.Get() might be preceeded by another call to s.Add() in another goroutine.

    If you need guarantee that noone else modifies or accesses the value of the Status.count field while you perform further calculations on it, then sync.Mutex or sync.RWMutex is the way to go, as you can hold a lock on the count field while you finish your calculations.

    Edit: To answer your edit:

    Direct access to s.count is not safe, atomic.LoadUint32(&s.count) is safe. Reason for this is because if goroutine #1 calls s.Add(), and goroutine #2 tries to access s.count, there is no guarantee that goroutine #2 will see changes made by #1. In #2 you may see just a cached version of s.count.

    Without explicit synchronization you have no guarantee to observe changes made to a variable in another goroutine. Directly accessing s.count is an unsynchronized access. Use of channels or other synchronization primitives (e.g. sync or sync/atomic packages) ensures serialized access to s.count, so these solutions will always see the current, updated value.

    For details, see this article: The Go Memory Model

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

报告相同问题?

悬赏问题

  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测