2 回答

TA貢獻(xiàn)1886條經(jīng)驗(yàn) 獲得超2個贊
GOMAXPROCS
由于運(yùn)行時會為您與操作系統(tǒng)進(jìn)行交互,因此您不需要在大多數(shù)時候搞砸。 GOMAXPROCS
過去默認(rèn)為 1,但在 Go 1.5 中,現(xiàn)在默認(rèn)為NumCPU()
將其設(shè)置為高于 NumCPU 只會為調(diào)度程序提供更多(不必要的)處理操作系統(tǒng)線程的工作。

TA貢獻(xiàn)1848條經(jīng)驗(yàn) 獲得超6個贊
最大值為 256;但請注意,如果您將其設(shè)置得更高,則不會出錯。
https://golang.org/src/runtime/debug.go?s=534:560#L7
12 // GOMAXPROCS sets the maximum number of CPUs that can be executing
13 // simultaneously and returns the previous setting. If n < 1, it does not
14 // change the current setting.
15 // The number of logical CPUs on the local machine can be queried with NumCPU.
16 // This call will go away when the scheduler improves.
17 func GOMAXPROCS(n int) int {
18 if n > _MaxGomaxprocs {
19 n = _MaxGomaxprocs
20 }
21 lock(&sched.lock)
22 ret := int(gomaxprocs)
23 unlock(&sched.lock)
24 if n <= 0 || n == ret {
25 return ret
26 }
27
28 stopTheWorld("GOMAXPROCS")
29
30 // newprocs will be processed by startTheWorld
31 newprocs = int32(n)
32
33 startTheWorld()
34 return ret
35 }
Line 19將總數(shù)設(shè)置為_MaxGomaxprocs。
這是...
https://golang.org/src/runtime/runtime2.go?h=_MaxGomaxprocs#L407
const (
// The max value of GOMAXPROCS.
// There are no fundamental restrictions on the value.
_MaxGomaxprocs = 1 << 8
)
二進(jìn)制形式的位移是100000000和 1 是int在 64 位系統(tǒng)上,Go 使其成為 Int64,這意味著最大值是 256。(intGo 中的32 位系統(tǒng)將是 int32,但值為 256)
現(xiàn)在,只要將其設(shè)置為多于您的內(nèi)核數(shù)量 - 這一切都取決于您的工作負(fù)載和正在發(fā)生的 CPU 上下文切換(例如,您的 go 程序強(qiáng)制發(fā)生多少鎖,或者您是否mutex.Lock()在任何地方使用等)。
請記住,無論是否需要,Golang 都會抽象出上下文切換。
基準(zhǔn)測試是您的朋友。如果您的應(yīng)用程序運(yùn)行 10,000 個 goroutine,而幾乎沒有 cpu 上下文切換(遵循良好的設(shè)計(jì)模式),那么是的,將那個吸盤提升到 256 并讓它運(yùn)行。如果您的應(yīng)用程序阻塞并通過上下文切換/線程創(chuàng)建大量 CPU 等待時間,則將其設(shè)置為 8 或 4,甚至可以在所有mutex鎖定進(jìn)行時為其提供喘息的空間。
- 2 回答
- 0 關(guān)注
- 286 瀏覽
添加回答
舉報(bào)