go已經越來越被重視了,特別適合大型互聯網公司基礎服務的編寫,高效,高並發,可以同時允許多個明星出軌,多個明星結婚 都不在話下,下面介紹下GO協程通訊的過程
直接上代碼
package main import ( "fmt" "time" ) func main() { //關於channel和routine的理解,一個描述挖礦的程序。它包含三個函數,分別負責執行尋礦、挖礦和練礦任務。 //在本例中,我們用一組字符串表示 rock(礦山) 和 ore(礦石),每個函數都以它們作為輸入,並返回一組 “處理過的” 字符串。 theMine := [5]string{"rock", "ore", "rock", "ore", "ore"} //建立兩個管道 oreChannel := make(chan string) mineChannel := make(chan string) //Finder 找到石頭后發送到管道oreChannel go func(mine [5]string) { for _, item := range mine { if item == "rock" { oreChannel <- item //send item on oreChannel } } }(theMine) //Ore Breaker //從管道oreChannel 中讀取 ore原石 /*go func() { for i := 0; i < 3; i++ { foundOre := <-oreChannel //read from oreChannel fmt.Println("From Finder", foundOre) mineChannel <- "mineOre" //send to mineOreChan } }() */ go func() { for foundOre := range oreChannel { fmt.Println("Miner: Received " + foundOre + " from finder") mineChannel <- foundOre } }() //Smelter //接收 go func() { for i := 0; i < 3; i++ { mineOre := <-mineChannel //read from mineChannel fmt.Println("From Miner:", mineOre) fmt.Println("From Smelter:Ore is smelter") } }() <-time.After(time.Second * 5) // }
最近學習的內容都記錄下方便以后復習查看