What causes this race condition

90 views
Skip to first unread message

st ov

unread,
Jun 20, 2018, 12:21:51 AM6/20/18
to golang-nuts
I'm trying to understand what is causing this race condition.

From what I can tell, this function will behave as expected.
The assignment will eventually end the for loop and execute the print statement.

Yet go test -race will detect a race condition.

Does the presence of any concurrent unprotected read trigger a data race, disregarding the logic as a whole?


  package main
 
 
import (  
     
"fmt"
     
"runtime"
 
)

  func main
() {  
     
done := false
 
      go func
(){
         
done = true
     
}()
 
     
for !done {
          runtime
.Gosched()
     
}
      fmt
.Println("done!")
 
}

  $ go run
-race racy.go
 
==================
  WARNING
: DATA RACE
 
Write at 0x00c42009800f by goroutine 6:
    main
.main.func1()
       
/home/eric/racy.go:12 +0x38
 
 
Previous read at 0x00c42009800f by main goroutine:
    main
.main()
       
/home/eric/racy.go:15 +0x8b
 
 
Goroutine 6 (running) created at:
    main
.main()
       
/home/eric/racy.go:11 +0x76
 
==================
 
done!
 
Found 1 data race(s)
 
exit status 66


Dave Cheney

unread,
Jun 20, 2018, 12:36:54 AM6/20/18
to golang-nuts
I recommend this, https://golang.org/doc/articles/race_detector.html

Specifically to your question, “ A data race occurs when two goroutines access the same variable concurrently and at least one of the accesses is a write. ”

st ov

unread,
Jun 20, 2018, 12:41:51 AM6/20/18
to golang-nuts
Thanks Dave, that answers my question.
Reply all
Reply to author
Forward
0 new messages