首页 > Go中能对结构体中的单个数据加锁么

Go中能对结构体中的单个数据加锁么

Go中能对结构体中的单个数据枷锁么

type x struct {
    a int
    b int
}

我只想给x中的a加锁能做到么


可以
使用 Mutex

type x struct {
    a int
    lock_a sync.Mutex
    b int
}

func (p *x) Geta() int {
    p.lock_a.Lock()
    defer p.lock_a.Unlock()
    return p.a
}

但是一般来说,对于 int 类型没必要加锁,除非有特别的时序要求

【热门文章】
【热门文章】