I want to make my program more efficient:
can I give a *sync.Mutex
variable to a struct so that when I execute a obj.Mutex.Lock()
it is locking just goroutines operation on that specific object?
example:
package main
import (
"fmt"
"sync"
"time"
)
type mystruct struct {
Counter int
Mutex *sync.Mutex
}
func (obj *mystruct) incrementCount() {
for i := 0; i < 1000; i++ {
obj.Mutex.Lock()
obj.Counter++
time.Sleep(time.Microsecond)
obj.Mutex.Unlock()
}
fmt.Println("incrementCount returns")
}
func funcNotSensibleToMutex() {
n := 0
for i := 0; i < 1000; i++ {
n++
time.Sleep(time.Microsecond)
}
fmt.Println("returns first since it's not affected by mutex")
}
func main() {
a := &mystruct{0, &sync.Mutex{}}
go a.incrementCount()
go a.incrementCount()
go funcNotSensibleToMutex()
time.Sleep(time.Duration(5) * time.Second)
fmt.Println("a counter", a.Counter)
}