普通网友 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 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥30 用arduino开发esp32控制ps2手柄一直报错
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 求chat4.0解答一道线性规划题,用lingo编程运行,第一问要求写出数学模型和lingo语言编程模型,第二问第三问解答就行,我的ddl要到了谁来求了
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥65 汇编语言除法溢出问题
  • ¥15 Visual Studio问题