introduce Mutex into the object to ensure atomicity, but when the object is a value reference, it is found that the cable has no effect. What is its internal implementation logic?
the code is as follows:
package main
import (
"fmt"
"sync"
)
//
type people struct {
sync.Mutex
}
//
func (p people) test(str string) {
p.Lock();
defer p.Unlock();
for i := 0; i < 5; {
fmt.Println(str, i)
iPP
}
}
func main() {
var user people
var wg sync.WaitGroup
wg.Add(2)
go func() {
defer wg.Done()
user.test("go1")
}()
go func() {
defer wg.Done()
user.test("go2")
}()
wg.Wait()
}
if executed in this way, you can"t see the effect, and then add this line of code:
func (p people) test(str string) {
p.Lock();
defer p.Unlock();
for i := 0; i < 5; {
fmt.Println(str, i)
//
time.Sleep(time.Second)
iPP
}
}
the result of discovery execution is as follows:
go2 0
go1 0
go2 1
go1 1
go1 2
go2 2
go2 3
go1 3
go1 4
go2 4
puzzling point: in the whole logic process, there is only one variable user, that does not copy the value, so how can the good lock not take effect?