package main import ( "fmt" "runtime" ) func main() { runtime.GOMAXPROCS(runtime.NumCPU()) c := make(chan bool, 10) for i := 0; i < 10; i++ { go Go(c, i) } for i := 0; i < 10; i++ { <-c } } func Go(c chan bool, index int) { a := 1 for i := 0; i < 100; i++ { a += i } fmt.Println(index, a) c <- true }
package main import ( "fmt" "runtime" "sync" ) func main() { runtime.GOMAXPROCS(runtime.NumCPU()) wg := sync.WaitGroup{} wg.Add(10) for i := 0; i < 10; i++ { go Go(&wg, i) } wg.Wait() } func Go(wg *sync.WaitGroup, index int) { a := 1 for i := 0; i < 100; i++ { a += i } fmt.Println(index, a) wg.Done() }
package main import ( "fmt" ) func main() { c := make(chan int) go func() { for v := range c { fmt.Println(v) } }() for { select { case c <- 0: case c <- 1: } } }参考: [1]. https://github.com/Unknwon/go-fundamental-programming/blob/master/lectures/lecture14.md
有疑问加站长微信联系(非本文作者)