Skip to content

Commit b1deac8

Browse files
committed
testdata: fix flaky goroutines test
The goroutines test had two races under thread-based scheduling: 1. "main 2" vs "sub 2": both printed around 100-200ms from start, racing on loaded systems. Fixed by using channel synchronization between main and sub() instead of relying on sleep timing. 2. "slept inside func pointer" vs "slept inside closure": both goroutines launched by sleepFuncValue slept 1ms then printed, with only a 1ms gap between launches. Fixed by waiting for each goroutine to complete via a done channel before starting the next. The test still exercises goroutine creation, function value calls, closure captures, and channel communication. Addresses tinygo-org/tinygo issue 4965.
1 parent e1c94d4 commit b1deac8

1 file changed

Lines changed: 12 additions & 6 deletions

File tree

testdata/goroutines.go

Lines changed: 12 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -11,12 +11,15 @@ func init() {
1111
time.Sleep(1 * time.Millisecond)
1212
}
1313

14+
var subCh = make(chan struct{})
15+
var sleepDone = make(chan bool)
16+
1417
func main() {
1518
println("main 1")
1619
go sub()
17-
time.Sleep(100 * time.Millisecond)
20+
<-subCh // wait for sub to print "sub 1"
1821
println("main 2")
19-
time.Sleep(200 * time.Millisecond)
22+
<-subCh // wait for sub to print "sub 2"
2023
println("main 3")
2124

2225
// Await a blocking call.
@@ -41,15 +44,16 @@ func main() {
4144
sleepFuncValue(func(x int) {
4245
time.Sleep(1 * time.Millisecond)
4346
println("slept inside func pointer", x)
47+
sleepDone <- true
4448
})
45-
time.Sleep(1 * time.Millisecond)
49+
<-sleepDone
4650
n := 20
4751
sleepFuncValue(func(x int) {
4852
time.Sleep(1 * time.Millisecond)
4953
println("slept inside closure, with value:", n, x)
54+
sleepDone <- true
5055
})
51-
52-
time.Sleep(2 * time.Millisecond)
56+
<-sleepDone
5357

5458
var x int
5559
go func() {
@@ -103,8 +107,10 @@ func acquire(m *sync.Mutex, wg *sync.WaitGroup) {
103107

104108
func sub() {
105109
println("sub 1")
106-
time.Sleep(200 * time.Millisecond)
110+
subCh <- struct{}{}
111+
time.Sleep(150 * time.Millisecond)
107112
println("sub 2")
113+
subCh <- struct{}{}
108114
}
109115

110116
func wait() {

0 commit comments

Comments
 (0)