You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
package main
import "sync"
type Payload struct {
A string
B string
}
func main() {
for i := 0; i < 20; i++ {
go func() {
for {
payload := &Payload{}
var wg sync.WaitGroup
wg.Add(1)
go func() {
defer wg.Done()
payload.A += "1"
}()
go func() {
payload.B += "1"
}()
wg.Wait()
if payload.A != payload.B { // Crash at here.
}
}
}()
}
<-make(chan bool)
}
What did you expect to see?
no panic
What did you see instead?
panic
panic: runtime error: invalid memory address or nil pointer dereference
[signal SIGSEGV: segmentation violation code=0x1 addr=0x0 pc=0x10023e7]
goroutine 23 [running]:
main.main.func1()
/private/var/folders/v2/xjx1mlfd43x39dxyyfjn64kr0000gp/T/CodeRunner/Go/Untitled 2.go:27 +0xf0
created by main.main
/private/var/folders/v2/xjx1mlfd43x39dxyyfjn64kr0000gp/T/CodeRunner/Go/Untitled 2.go:12 +0x3e
Why it crashed when string comparison?
Consider the following example
package main
type Payload struct {
A string
B string
}
func main() {
payload := &Payload{}
for i:=0;i<100;i++{
go func(){
for {
payload.A += "1"
if payload.A != payload.B { // no crash
}
}
}()
go func(){
for {
payload.B += "1"
if payload.A != payload.B { // no crash
}
}
}()
}
<- make(chan int)
}
The text was updated successfully, but these errors were encountered:
twz915
changed the title
unexpected panic when struct fields comparison when sync.WaitGroup misuse
unexpected panic when struct fields comparison with sync.WaitGroup misuse
Jan 10, 2020
There is a race in your code; the second small goroutine does not refer to the wait group at all. If you add that in, and adjust the wg.Add call to take that into account, the code works as expected.
I agree: this has nothing to do with sync.WaitGroup or with accessing different member of structs. You have a race on a string value: one goroutine is reading it while another goroutine is simultaneously writing to it. That can lead to a crash.
I'm going to close this since I don't think there is anything to change in the Go tools or libraries. You may want to look into using the race detector (https://golang.org/doc/articles/race_detector.html).
Races are unpredictable. There may be a reason why that program doesn't crash, but I don't know what it is, and I don't think it matters. Programs with race conditions are never safe in Go. Don't write them. Use the race detector.
What version of Go are you using (
go version
)?Does this issue reproduce with the latest release?
yes
What operating system and processor architecture are you using (
go env
)?go env
OutputWhat did you do?
What did you expect to see?
no panic
What did you see instead?
panic
I googled these links
Why it crashed when string comparison?
Consider the following example
The text was updated successfully, but these errors were encountered: