標籤:退出 cpu ack 垃圾 記憶體 package 並行計算 也會 回收機制
goroutine
// code_037_concurrency_goroutine project main.gopackage mainimport ( "fmt" "time")//並發,concurrency; 並行,parallel;而Go從語言層面就支援了並行,而Go語言提供了自動記憶體回收機制。//goroutine說到底其實就是協程,執行goroutine只需極少的棧記憶體(大概是4~5KB),當然會根據相應的資料伸縮func newTask() { i := 0 for { i++ fmt.Printf("new gorotine: i= %d\n", i) time.Sleep(1 * time.Second) if i == 10 { break } }}func main() { go newTask() //goroutine>>> 主goroutine退出後,其它的工作goroutine也會自動結束 i := 0 for { i++ fmt.Printf("main goroutine : i =%d\n", i) time.Sleep(1 * time.Second) if i == 10 { break } }}
Goexit >>>
// code_039_goroutine_runtime_Goexit project main.gopackage mainimport ( "fmt" "runtime")//備忘:調用 runtime.Goexit() 將立即終止當前 goroutine 執?,調度器確保所有登入 defer延遲調用被執行。func main() { go func() { defer fmt.Println("A.defer") func() { defer fmt.Println("B.defer") runtime.Goexit() // 終止當前 goroutine, import "runtime" fmt.Println("B") //不會執行 }() fmt.Println("A") //不會執行 }() //死迴圈,目的不讓主goroutine結束 for { }}
Gosched >>>
// code_038_goroutine_runtime project main.gopackage mainimport ( "fmt" "runtime")func main() { //runtime包:Gosched()、Goexit()、GOMAXPROCS() //runtime.Gosched() 用於讓出CPU時間片,讓出當前goroutine的執行許可權,調度器安排其他等待的任務運行,並在下次某個時候從該位置恢複執行。 //調用 runtime.Goexit() 將立即終止當前 goroutine 執行,調度器確保所有登入 defer延遲調用被執行。 //調用 runtime.GOMAXPROCS() 用來設定可以並行計算的CPU核心數的最大值,並返回之前的值。 go func(s string) { for i := 0; i < 5; i++ { fmt.Println(s) } }("world") for i := 0; i < 5; i++ { runtime.Gosched() fmt.Println("Hello") }}
GOMAXPROCS >>>
// code_040_goroutine_runtime_GOMAXPROCS project main.gopackage mainimport ( "fmt" "runtime")//調用 runtime.GOMAXPROCS() 用來設定可以並行計算的CPU核心數的最大值,並返回之前的值。func main() { n := runtime.GOMAXPROCS(1) // n := runtime.GOMAXPROCS(2) fmt.Printf("n=%d\n", n) for { go fmt.Print(0) fmt.Print(1) }}
goroutine/Gosched/Goexit/GOMAXPROCS