go_study/bilibili/aceld/goroutine/channel/test2/main.go

36 lines
748 B
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// 有缓冲的channel
package main
import (
"fmt"
"time"
)
func main() {
c := make(chan int, 3) // 带有缓冲的channel
fmt.Println("len(c) = ", len(c), ", cap(c) = ", cap(c))
// 做一个go程
go func() {
defer fmt.Println("子go程结束")
// 如果循环3将不会阻塞大于3就会阻塞
for i := 0; i < 4; i++ {
// 把i传递给channel
c <- i
fmt.Println("子go程正在运行, 发送元素: ", i, ", len(c) = ", len(c), ", cap(c) = ", cap(c))
}
}()
time.Sleep(2 * time.Second)
for i := 0; i < 4; i++ {
num := <-c
fmt.Println("num = ", num)
// 如果这里不阻塞的话那么子go程在第2轮之后有可能不会打印
time.Sleep(1 * time.Second)
}
fmt.Println("主进程main结束")
}