Golang中runtime的使用詳解
runtime 調(diào)度器是個(gè)非常有用的東西,關(guān)于 runtime 包幾個(gè)方法:
- Gosched:讓當(dāng)前線程讓出 cpu 以讓其它線程運(yùn)行,它不會(huì)掛起當(dāng)前線程,因此當(dāng)前線程未來會(huì)繼續(xù)執(zhí)行
- NumCPU:返回當(dāng)前系統(tǒng)的 CPU 核數(shù)量
- GOMAXPROCS:設(shè)置最大的可同時(shí)使用的 CPU 核數(shù)
- Goexit:退出當(dāng)前 goroutine(但是defer語句會(huì)照常執(zhí)行)
- NumGoroutine:返回正在執(zhí)行和排隊(duì)的任務(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)
}
運(yùn)行結(jié)果:

GOMAXPROCS
Golang 默認(rèn)所有任務(wù)都運(yùn)行在一個(gè) cpu 核里,如果要在 goroutine 中使用多核,可以使用 runtime.GOMAXPROCS 函數(shù)修改,當(dāng)參數(shù)小于 1 時(shí)使用默認(rèn)值。
package main
import (
"fmt"
"runtime"
)
func init() {
runtime.GOMAXPROCS(1)
}
func main() {
// 任務(wù)邏輯...
}
Gosched
這個(gè)函數(shù)的作用是讓當(dāng)前 goroutine 讓出 CPU,當(dāng)一個(gè) goroutine 發(fā)生阻塞,Go 會(huì)自動(dòng)地把與該 goroutine 處于同一系統(tǒng)線程的其他 goroutine 轉(zhuǎn)移到另一個(gè)系統(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é)果:

使用多核測(cè)試:
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è)定運(yùn)行時(shí)的核數(shù),但是運(yùn)行結(jié)果不一定與上面相同,或者在 main 函數(shù)的最后加上 select{} 讓程序阻塞,則結(jié)果如下:

多核比較適合那種 CPU 密集型程序,如果是 IO 密集型使用多核會(huì)增加 CPU 切換的成本。
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Golang官方限流器庫實(shí)現(xiàn)限流示例詳解
這篇文章主要為大家介紹了Golang官方限流器庫使用示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-08-08
Golang實(shí)現(xiàn)Redis分布式鎖(Lua腳本+可重入+自動(dòng)續(xù)期)
本文主要介紹了Golang分布式鎖實(shí)現(xiàn),采用Redis+Lua腳本確保原子性,持可重入和自動(dòng)續(xù)期,用于防止超賣及重復(fù)下單,具有一定的參考價(jià)值,感興趣的可以了解一下2025-05-05

