dela18
(Protocl18)
April 14, 2023, 4:53am
1
package main
import (
“fmt”
“runtime”
“sync”
)
var wg sync.WaitGroup
func main() {
fmt.Println(“GoRoutine:”, runtime.NumGoroutine())
fmt.Println(“NumCPU:”, runtime.NumCPU())
cnt:= 0
const gs = 100
wg.Add(gs)
var mtx sync.Mutex
for i := 0; i < gs; i++ {
go func() {
mtx.Lock()
v := cnt
v++
runtime.Gosched()
cnt= v
mtx.Unlock()
wg.Done()
}()
fmt.Println("GoRoutine:", runtime.NumGoroutine())
}
fmt.Println("cnt:", cnt)
wg.Wait()
}
caster
(caster)
April 14, 2023, 8:23am
2
try this
package main
import (
"fmt"
"runtime"
"sync"
)
var wg sync.WaitGroup
func main() {
fmt.Println("GoRoutine:", runtime.NumGoroutine())
fmt.Println("NumCPU:", runtime.NumCPU())
cnt := 0
const gs = 100
wg.Add(gs)
var mtx sync.Mutex
for i := 0; i < gs; i++ {
go func() {
mtx.Lock()
v := cnt
v++
runtime.Gosched()
cnt = v
mtx.Unlock()
wg.Done()
}()
fmt.Println("GoRoutine:", runtime.NumGoroutine())
}
wg.Wait()
fmt.Println("cnt:", cnt)
}
1 Like
dela18
(Protocl18)
April 14, 2023, 3:55pm
3
Hi caster !
thank youu
Any explication of the why? anyway thanks a lot
mje
(Jeff Emanuel)
April 14, 2023, 4:51pm
4
Because you were printing cnt
from the main goroutine before waiting until all the cnt
-incrementing goroutines finished, it printed cnt
at some indeterminable time before all those goroutines completed.
You could have locked the mutex in the main goroutine around printing cnt
, but it would still be indeteriminable which value of cnt
got printed.
1 Like