go - How to apply separate Mutex on multiple variables in Golang? -
i have multiple variables want make mutually exclusive using 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 hundreds of variable, var1, var2, var3.... var100
how make of them mutually exclusive without repeating code?
note var1, var2, var3 etc not part of array , no way related each other. var2 may int , var3 may user{}
you make different mutex object 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 this
func main() { := mutexint{v: 0} i.lock() i.set(2) fmt.println(i.get()) i.unlock() }
Comments
Post a Comment