Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 12 additions & 1 deletion src/sync/waitgroup.go
Original file line number Diff line number Diff line change
Expand Up @@ -236,7 +236,18 @@ func (wg *WaitGroup) Wait() {
func (wg *WaitGroup) Go(f func()) {
wg.Add(1)
go func() {
defer wg.Done()
defer func() {
if x := recover(); x != nil {
// Don't call Done as it may cause Wait to unblock,
// so that the main goroutine races with the runtime.fatal
// resulting from unhandled panic.
panic(x)
}

// f completed normally, or abruptly using goexit.
// Either way, decrement the semaphore.
wg.Done()
}()
f()
}()
}
38 changes: 38 additions & 0 deletions src/sync/waitgroup_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,12 @@
package sync_test

import (
"bytes"
"internal/testenv"
"os"
"os/exec"
"strings"
"sync"
. "sync"
"sync/atomic"
"testing"
Expand Down Expand Up @@ -110,6 +116,38 @@ func TestWaitGroupGo(t *testing.T) {
}
}

// This test ensures that an unhandled panic in a Go goroutine terminates
// the process without causing Wait to unblock; previously there was a race.
func TestIssue76126(t *testing.T) {
testenv.MustHaveExec(t)
// Call child in a child process
// and inspect its failure message.
cmd := exec.Command(os.Args[0], "-test.run=^TestIssue76126Child$")
cmd.Env = append(os.Environ(), "SYNC_TEST_CHILD=1")
buf := new(bytes.Buffer)
cmd.Stderr = buf
cmd.Run() // ignore error

got := buf.String()
if strings.Contains(got, "panic: test") {
// ok
} else {
t.Errorf("missing panic: test\n%s", got)
}
}

func TestIssue76126Child(t *testing.T) {
if os.Getenv("SYNC_TEST_CHILD") != "1" {
t.Skip("not child")
}
var wg sync.WaitGroup
wg.Go(func() {
panic("test")
})
wg.Wait() // process should terminate here
panic("Wait returned") // must not be reached
}

func BenchmarkWaitGroupUncontended(b *testing.B) {
type PaddedWaitGroup struct {
WaitGroup
Expand Down