dongyuhui0418 2014-11-19 15:34
浏览 222
已采纳

如何在Golang中的多个变量上应用单独的Mutex?

I have multiple variables which I want to make mutually exclusive using this method

type var1WithMutex struct {
    mu       sync.Mutex
    var1     int
}
func (v *var1) Set(value int) {
    v.mu.Lock()
    v.var1 = value
    v.mu.Unlock()
}
func (v *var1) Get() (value int) {
    v.mu.Lock()
    value = v.var1
    v.mu.Unlock()
    return
}

Similarly there are hundreds of variable, like var1, var2, var3.... var100
How do i make all of them mutually exclusive without repeating this code?
Note that var1, var2, var3 etc are not part of an array and no way related to each other. var2 may be a int and var3 may be User{}

  • 写回答

3条回答 默认 最新

  • duanpu1111 2014-11-19 16:44
    关注

    You could make different Mutex object for each type instead. Playground

    type MutexInt struct {
        sync.Mutex
        v int
    }
    
    func (i *MutexInt) Get() int {
        return i.v
    }
    
    func (i *MutexInt) Set(v int) {
        i.v = v
    }
    

    and use it like this

    func main() {
        i := MutexInt{v: 0}
        i.Lock()
        i.Set(2)
        fmt.Println(i.Get())
        i.Unlock()
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥50 三种调度算法报错 有实例
  • ¥15 关于#python#的问题,请各位专家解答!
  • ¥200 询问:python实现大地主题正反算的程序设计,有偿
  • ¥15 smptlib使用465端口发送邮件失败
  • ¥200 总是报错,能帮助用python实现程序实现高斯正反算吗?有偿
  • ¥15 对于squad数据集的基于bert模型的微调
  • ¥15 为什么我运行这个网络会出现以下报错?CRNN神经网络
  • ¥20 steam下载游戏占用内存
  • ¥15 CST保存项目时失败
  • ¥20 java在应用程序里获取不到扬声器设备