golang中sync.WaitGroup的作用类似于channel,可实现并发。
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 f(&wg, i)
}
wg.Wait()
}
func f(w *sync.WaitGroup, i int) {
fmt.Println(i, "go")
w.Done()
}
golang中select是配合channel使用的。
package main
import (
"fmt"
"runtime"
)
func main() {
runtime.GOMAXPROCS(runtime.NumCPU())
c1, c2 := make(chan int), make(chan string)
flag := make(chan bool, 2)
go func() {
for {
select {
case k, err := <-c1:
if !err {
flag <- true
break
}
fmt.Println(k)
case k, err := <-c2:
if !err {
flag <- true
break
}
fmt.Println(k)
}
}
}()
c1 <- 1
c2 <- "a"
c1 <- 2
c2 <- "b"
close(c1)
close(c2)
for i := 0; i < 2; i++ {
<-flag
}
}
有疑问加站长微信联系(非本文作者)