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

如何在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{}

图片转代码服务由CSDN问答提供 功能建议

我想使用此方法使多个变量互斥
\ n

 类型var1WithMutex结构{
 mu sync.Mutex 
 var1 int 
} 
func(v * var1)Set(value int){
 v.mu.Lock()
 v。  var1 = value 
 v.mu.Unlock()
} 
func(v * var1)Get()(值int){
 v.mu.Lock()
 value = v.var1 
 v。  mu.Unlock()
 return 
} 
   
 
 

类似地,还有数百个变量,例如var1,var2,var3。...var100
\ n我如何在不重复此代码的情况下使它们互斥?
请注意,var1,var2,var3等不是数组的一部分,并且彼此之间没有关联。 var2可以是一个int,而var3可以是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()
    }
    
    点赞 评论
  • doupeizheng3918 2014-11-19 19:04

    You can wrap your variables and use a shared mutex, if they all have the same interface (http://play.golang.org/p/xri2M-rtEY):

    type Var interface {
        Get() int
        Set(n int)
    }
    
    func Sync(v Var, m *sync.RWMutex) Var {
        return &syncedVar{
            v: v,
            m: m,
        }
    }
    
    type syncedVar struct {
        m *sync.RWMutex
        v Var
    }
    
    func (v syncedVar) Get() int {
        v.m.RLock()
        defer v.m.RUnlock()
        return v.v.Get()
    }
    
    func (v *syncedVar) Set(n int) {
        v.m.Lock()
        defer v.m.Unlock()
        v.v.Set(n)
    }
    
    点赞 评论
  • doulun1939 2017-03-15 08:06

    If your variables are primitive data types (int, float,..), use the sync.atomic package. Atomic operations do not need mutex.

    点赞 评论

相关推荐 更多相似问题