github.com/nibnait/go-learn@v0.0.0-20220227013611-dfa47ea6d2da/src/test/chapter/ch4/33_util_all_done_test.go (about)

     1  package ch4
     2  
     3  import (
     4  	"fmt"
     5  	"runtime"
     6  	"testing"
     7  	"time"
     8  )
     9  
    10  func runTask(id int) string {
    11  	time.Sleep(10 * time.Millisecond)
    12  	return fmt.Sprintf("The result is from %d", id)
    13  }
    14  
    15  func AllResponse() string {
    16  	numOfRunner := 10
    17  	ch := make(chan string, numOfRunner)
    18  
    19  	for i := 0; i < numOfRunner; i++ {
    20  		go func(i int) {
    21  			ret := runTask(i)
    22  			ch <- ret
    23  		}(i)
    24  	}
    25  
    26  	finalRet := ""
    27  	for j := 0; j < numOfRunner; j++ {
    28  		finalRet += <-ch + "\n"
    29  	}
    30  
    31  	return finalRet
    32  }
    33  
    34  func TestAllResponse(t *testing.T) {
    35  	t.Log("Before:", runtime.NumGoroutine())
    36  	t.Log("finalRet: \n", AllResponse())
    37  	time.Sleep(time.Second * 1)
    38  	t.Log("After:", runtime.NumGoroutine())
    39  
    40  }