go-deep icon indicating copy to clipboard operation
go-deep copied to clipboard

update to fix data race

Open IrisesD opened this issue 5 months ago • 0 comments

For now, the Shuffle() function in training/model.go is:

func (e Examples) Shuffle() {
	for i := range e {
		j := rand.Intn(i + 1)
		e[i], e[j] = e[j], e[i]
	}
}

which uses the rand.Intn and performs write in a concurrent way. When the Shuffle() function is called in a concurrent way, there will be race condition error:

WARNING: DATA RACE
Read at 0x00c0001280c0 by goroutine 25:
  github.com/patrikeh/go-deep/training.Examples.Shuffle()
      /Users/xxx/go/pkg/mod/github.com/patrikeh/[email protected]/training/model.go:18 +0xd5
  github.com/patrikeh/go-deep/training.(*OnlineTrainer).Train()
      /Users/xxx/go/pkg/mod/github.com/patrikeh/[email protected]/training/trainer.go:54 +0x40d
  test.BenchmarkShuffle.func3()
      /Users/xxx/Desktop/Train.go:51 +0xba

Previous write at 0x00c0001280c0 by goroutine 24:
  github.com/patrikeh/go-deep/training.Examples.Shuffle()
      /Users/xxx/go/pkg/mod/github.com/patrikeh/[email protected]/training/model.go:18 +0x1b9
  github.com/patrikeh/go-deep/training.(*OnlineTrainer).Train()
      /Users/xxx/go/pkg/mod/github.com/patrikeh/[email protected]/training/trainer.go:54 +0x40d
  test.BenchmarkShuffle.func2()
      /Users/xxx/Desktop/Train.go:50 +0xba

I suggest we should add a mutex lock to the function, as this PR does.

IrisesD avatar Jan 16 '24 09:01 IrisesD