协程管理器
var wg sync.WaitGroup
wg.Add()
wg.Done()
wg.Wait()
func main() {// time starttime_start := time.Now()wg := sync.WaitGroup{}wg.Add(1)go run(&wg)wg.Wait()timeEnd := time.Since(time_start)fmt.Println("time cost: ", timeEnd.Nanoseconds())
}func run(wg *sync.WaitGroup) {fmt.Println("run")wg.Done()
}
channel 是 goroutine 之间的通信桥梁
定义 chan 分五种
可读可取 c:= make(chan int)
只读 c:= make(<-chan int)
只写 c:= make(chan<- int)
缓冲 c:= make(chan int, 10)
无缓冲 c:= make(chan int)
// 有缓冲区可以这样执行c := make(chan int, 1)c <- 1b := <-cfmt.Println(b)// 无缓冲区示例, 加了 go 异步执行 自执行函数d := make(chan int)go func() {d <- 1}()fmt.Println(<-d)
channel close 之后可以读,不能存
c := make(chan int, 5)
c <- 1
c <- 1
c <- 1
close(c)
c <- 4
//panic: send on closed channel // 不能存
用 for range 方法取 channel 里面的值,必须close
c := make(chan int, 5)
c <- 1
c <- 2
c <- 3
c <- 4
close(c)
for i := range c {println(i)
}
select 语句
c := make(chan int, 5)c2 := make(chan int, 5)c3 := make(chan int, 5)c <- 1//c2 <- 2//c3 <- 3// c,c2,c3 全部有值时,随机选择一个case执行select {case <-c:println("c")case <-c2:println("c2")case <-c3:println("c3")default:println("default")}
另一个例子
func main() {c := make(chan int)var readC <-chan int = cvar writeC chan<- int = cgo setChan(writeC)readChan(readC)
}func setChan(writeC chan<- int) {writeC <- 1
}func readChan(readC <-chan int) {fmt.Println(<-readC)
}