Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to apply separate Mutex on multiple variables in Golang?

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{}

like image 493
Rahul Prasad Avatar asked Mar 18 '23 20:03

Rahul Prasad


1 Answers

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()
}
like image 117
km6zla Avatar answered Mar 20 '23 08:03

km6zla