Go语言并发例子
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
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。