Open BubbleBear opened 5 years ago
package main
import (
"fmt"
"sync"
)
func main() {
c := counter{}
wg := sync.WaitGroup{}
for i := 0; i < 1000; i++ {
wg.Add(1)
go (func() {
c.inc()
defer wg.Done()
})()
}
wg.Wait()
fmt.Println(c.v)
}
type counter struct {
v int
mux sync.Mutex
}
func (c *counter) inc() {
c.mux.Lock()
c.v++
c.mux.Unlock()
}
here is what i suppose to be right.
package main import ( "fmt" "sync" ) func main() { c := counter{} wg := sync.WaitGroup{} for i := 0; i < 1000; i++ { wg.Add(1) go (func() { c.inc() defer wg.Done() })() } wg.Wait() fmt.Println(c.v) } type counter struct { v int mux sync.Mutex } func (c *counter) inc() { c.mux.Lock() c.v++ c.mux.Unlock() }
here is what i suppose to be right.
Jesus f***** Christ! Man, thank you SO MUCH, I'v just saved a ton of time making sense of it.
also I love your code design. main above, then type, then foo
Context: https://tour.golang.org/concurrency/9
with all due respect, the code example in sync.Mutex is so very wrong. i posted it here below. the section names sync.Mutex but the key that keeps it working is not sync.Mutex, but time.Sleep.
if you delete line:37 "time.Sleep(time.Second)", the output isn't 1000 anymore (when Value method is called, there are still Inc methods running or pending). while if you keep this line and delete all sync.Mutex related code, it works as well (perhaps it's because the virtual environment has only one CPU core).
though sync.Mutex doesn't make the Value method to block until all Inc methods done, the results above is way too misguiding.