Source file src/runtime/testdata/testprog/synctest.go

     1  // Copyright 2025 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package main
     6  
     7  import (
     8  	"internal/synctest"
     9  	"sync"
    10  )
    11  
    12  func init() {
    13  	register("SynctestCond/signal/no_bubble", func() {
    14  		synctestCond(func(cond *sync.Cond) {
    15  			cond.Signal()
    16  		})
    17  	})
    18  	register("SynctestCond/broadcast/no_bubble", func() {
    19  		synctestCond(func(cond *sync.Cond) {
    20  			cond.Broadcast()
    21  		})
    22  	})
    23  	register("SynctestCond/signal/other_bubble", func() {
    24  		synctestCond(func(cond *sync.Cond) {
    25  			synctest.Run(cond.Signal)
    26  		})
    27  	})
    28  	register("SynctestCond/broadcast/other_bubble", func() {
    29  		synctestCond(func(cond *sync.Cond) {
    30  			synctest.Run(cond.Broadcast)
    31  		})
    32  	})
    33  }
    34  
    35  func synctestCond(f func(*sync.Cond)) {
    36  	var (
    37  		mu     sync.Mutex
    38  		cond   = sync.NewCond(&mu)
    39  		readyc = make(chan struct{})
    40  		wg     sync.WaitGroup
    41  	)
    42  	defer wg.Wait()
    43  	wg.Go(func() {
    44  		synctest.Run(func() {
    45  			go func() {
    46  				mu.Lock()
    47  				defer mu.Unlock()
    48  				cond.Wait()
    49  			}()
    50  			synctest.Wait()
    51  			<-readyc // #1: signal that cond.Wait is waiting
    52  			<-readyc // #2: wait to continue
    53  			cond.Signal()
    54  		})
    55  	})
    56  	readyc <- struct{}{}
    57  	f(cond)
    58  }
    59  

View as plain text