Golang中runtime的使用詳解
runtime 調(diào)度器是個非常有用的東西,關(guān)于 runtime 包幾個方法:
- Gosched:讓當(dāng)前線程讓出 cpu 以讓其它線程運行,它不會掛起當(dāng)前線程,因此當(dāng)前線程未來會繼續(xù)執(zhí)行
- NumCPU:返回當(dāng)前系統(tǒng)的 CPU 核數(shù)量
- GOMAXPROCS:設(shè)置最大的可同時使用的 CPU 核數(shù)
- Goexit:退出當(dāng)前 goroutine(但是defer語句會照常執(zhí)行)
- NumGoroutine:返回正在執(zhí)行和排隊的任務(wù)總數(shù)
- GOOS:目標(biāo)操作系統(tǒng)
NumCPU
package main import ( "fmt" "runtime" ) func main() { fmt.Println("cpus:", runtime.NumCPU()) fmt.Println("goroot:", runtime.GOROOT()) fmt.Println("archive:", runtime.GOOS) }
運行結(jié)果:
GOMAXPROCS
Golang 默認(rèn)所有任務(wù)都運行在一個 cpu 核里,如果要在 goroutine 中使用多核,可以使用 runtime.GOMAXPROCS 函數(shù)修改,當(dāng)參數(shù)小于 1 時使用默認(rèn)值。
package main import ( "fmt" "runtime" ) func init() { runtime.GOMAXPROCS(1) } func main() { // 任務(wù)邏輯... }
Gosched
這個函數(shù)的作用是讓當(dāng)前 goroutine 讓出 CPU,當(dāng)一個 goroutine 發(fā)生阻塞,Go 會自動地把與該 goroutine 處于同一系統(tǒng)線程的其他 goroutine 轉(zhuǎn)移到另一個系統(tǒng)線程上去,以使這些 goroutine 不阻塞
package main import ( "fmt" "runtime" ) func init() { runtime.GOMAXPROCS(1) //使用單核 } func main() { exit := make(chan int) go func() { defer close(exit) go func() { fmt.Println("b") }() }() for i := 0; i < 4; i++ { fmt.Println("a:", i) if i == 1 { runtime.Gosched() //切換任務(wù) } } <-exit }
結(jié)果:
使用多核測試:
package main import ( "fmt" "runtime" ) func init() { runtime.GOMAXPROCS(4) //使用多核 } func main() { exit := make(chan int) go func() { defer close(exit) go func() { fmt.Println("b") }() }() for i := 0; i < 4; i++ { fmt.Println("a:", i) if i == 1 { runtime.Gosched() //切換任務(wù) } } <-exit }
結(jié)果:
根據(jù)你機(jī)器來設(shè)定運行時的核數(shù),但是運行結(jié)果不一定與上面相同,或者在 main 函數(shù)的最后加上 select{} 讓程序阻塞,則結(jié)果如下:
多核比較適合那種 CPU 密集型程序,如果是 IO 密集型使用多核會增加 CPU 切換的成本。
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Golang實現(xiàn)Redis分布式鎖(Lua腳本+可重入+自動續(xù)期)
本文主要介紹了Golang分布式鎖實現(xiàn),采用Redis+Lua腳本確保原子性,持可重入和自動續(xù)期,用于防止超賣及重復(fù)下單,具有一定的參考價值,感興趣的可以了解一下2025-05-05