Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

sync: Data race happen when using sync.WaitGroup #23842

Closed
DrmagicE opened this issue Feb 15, 2018 · 2 comments
Closed

sync: Data race happen when using sync.WaitGroup #23842

DrmagicE opened this issue Feb 15, 2018 · 2 comments

Comments

@DrmagicE
Copy link

DrmagicE commented Feb 15, 2018

I run the below code with race detector

package main

import (
	"sync"
)

func main() {
	var m *sync.WaitGroup
	m = &sync.WaitGroup{}
	for i := 0; i < 100; i++ {
		go func(m *sync.WaitGroup) {
			m.Add(1)
		}(m)
	}
	m.Wait()
}

and got a data race warning:

WARNING: DATA RACE
Write at 0x00c04200e03c by main goroutine:
  internal/race.Write()
      D:/Go/src/internal/race/race.go:41 +0x3f
  sync.(*WaitGroup).Wait()
      D:/Go/src/sync/waitgroup.go:129 +0xfb
  main.main()
      C:/Users/Lifang/go/src/ago.go:15 +0xbb

Previous read at 0x00c04200e03c by goroutine 5:
  internal/race.Read()
      D:/Go/src/internal/race/race.go:37 +0x3f
  sync.(*WaitGroup).Add()
      D:/Go/src/sync/waitgroup.go:71 +0x176
  main.main.func1()
      C:/Users/Lifang/go/src/ago.go:12 +0x48

I am confused.. Is it the Add() function should not call in other goroutine?

@DrmagicE DrmagicE reopened this Feb 15, 2018
@davecheney
Copy link
Contributor

This is not a bug, because Add is being called in a separate goroutine, it is executing concurrently with the call to Wait.

Don’t do that, call add outside the go statement.

https://golang.org/pkg/sync/#WaitGroup.Add

@DrmagicE
Copy link
Author

@davecheney Thanks!

@mikioh mikioh changed the title Data race happen when using sync.WaitGroup sync: Data race happen when using sync.WaitGroup Feb 21, 2018
@golang golang locked and limited conversation to collaborators Feb 21, 2019
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Projects
None yet
Development

No branches or pull requests

3 participants