Why i get data race using mutex?

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()

}

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

Hi caster !

thank youu :heart:

Any explication of the why? anyway thanks a lot :smile:

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

Thanks a lot @mje :heart: :pray:

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.