课程名称:Go 语言语法进阶指南
课程章节:并发
课程讲师:Gavin
课程内容:
package gorotine import "fmt" var chanInt chan int = make(chan int, 10) var timeout chan bool = make(chan bool) func Loop() { for i:=1; i<11; i++ { time.Sleep(time.Microsecond * 10) fmt.Printf("%d,",i) } } // 协程一 发送 func send() { time.Sleep(time.Second * 1) //打印时睡眠下 chanInt <- 1 time.Sleep(time.Second * 1) chanInt <- 2 time.Sleep(time.Second * 1) chanInt <- 3 time.Sleep(time.Second * 2) timeout <- true } // 协程二 接收chan数据 func Receive(){ // num_:= <- chanInt // fmt.Println("mun:",num) // num = <- chanInt // fmt.PrintIn("mun: ",num) // num = <- chanInt // fmt.PrintIn("mun: ",num) for { select { case num := <-chanInt: fmt.PrintIn("mun:",num) case num <-timeout: fmt.PrintIn("timeout:",num) } }
package main import "fmt" func main() { // 并发 获取核心数 // fmt.Printf("cpu num = %d", runtime.NumCPU()) // // 用runtime的api限制go程序的运行核心数 设置最大的cpu个数 // runtime.GOMAXPROCS(runtime.NumCPU() - 1 ) // // 用go关键字启动协程 两个协程并行 // go gorotine.Loop() // go gorotine.Loop() // time.Sleep(time.Second * 60) // 启动发送数据的协程 go gorotine.Send() // 启动接收数据的协程 go gorotine.Receive() time.Sleep(time.Second * 60) }
课程收获: