github.com/ks888/tgo@v0.0.0-20190130135156-80bf89407292/testutils/testdata/goroutines.go (about)

     1  package main
     2  
     3  import (
     4  	"fmt"
     5  	"time"
     6  )
     7  
     8  //go:noinline
     9  func receive(ch chan int) int {
    10  	return <-ch
    11  }
    12  
    13  //go:noinline
    14  func send(ch chan int, val int) {
    15  	ch <- val
    16  }
    17  
    18  func inc(input, output chan int) {
    19  	val := receive(input)
    20  	send(output, val+1)
    21  }
    22  
    23  func main() {
    24  	chans := []chan int{make(chan int)}
    25  	for i := 0; i < 20; i++ {
    26  		fromCh := chans[len(chans)-1]
    27  		var toCh = make(chan int)
    28  		go inc(fromCh, toCh)
    29  
    30  		chans = append(chans, toCh)
    31  	}
    32  
    33  	chans[0] <- 0
    34  	val := <-chans[len(chans)-1]
    35  	fmt.Println(val)
    36  
    37  	// the main go routine may exit before all go routines created above exit and tracing ends.
    38  	time.Sleep(100 * time.Millisecond)
    39  }