go 關鍵字跟隨的函數,異步執行,並且可以阻塞,類似於js 的 async 函數中 await 異步結果
協程間通過 channel 傳遞信息,並且 channel 帶有阻塞性,加上 go函數 的阻塞性,所以函數編寫類似串行執行
但還是要注意是異步執行,結果出現的時間和串行不同。
package main import( "fmt" "time" ) var ch chan int = make(chan int,2); func chPush(){ fmt.Println("before push.") for i:=0;i<5;i++{ // time.Sleep(100*time.Millisecond)
// 必須要讀取以後,才能再壓入一個。容量是2,所以一次可以壓入2個數據
ch <- i
fmt.Println("push:",i) } fmt.Println("after push.") } func chPop(){ fmt.Println("before pop.") for i:=0;i<5;i++{ time.Sleep(100*time.Millisecond)
// 堵塞,必須要有數據,才能讀取。另外,此處讀取一個數據,chPush 會立即壓入一個數據
n := <- ch fmt.Println("pop:",n) }
fmt.Println("after pop.")
}
func main(){
fmt.Println("begin:")
go chPush() // 異步,不會等待
fmt.Println("follow go push. no choke")
time.Sleep(1000 * time.Millisecond)
go chPop()
fmt.Println("follow go pop. no choke but delayed by sleep")
// 主線程可能會先於子協程結束,所以要某種方式等待一下
time.Sleep(1000 * time.Millisecond)
fmt.Println("end.")
}