1 回答

TA貢獻1827條經驗 獲得超8個贊
大約 2 個月前(或更多)語言開發人員談到侵入線程計數控制(和一些其他限制)。所以我們可以期待很快看到它。一個月或更長時間前,我開發了這個問題,在我的 linux 機器上發現 GOMAXPROCS 沒有超過 256 的值。如果我向它發送 300 或更多,結果總是 256。但我發現 goroutines 不是線程。Goroutines 可以存在于一個線程中。
至于慣用同步 - 我認為沒有必要同步太多。在我的代碼中,我通常使用 goroutine 僅通過通道進行通信的想法。通道應該作為 goroutine 的參數傳遞。
func main() {
ch1 := make(chan SomeType1)
ch2 := make(chan SomeType2)
go generator(ch1, ch2)
go processor(ch1, ch2)
// here main func becomes waiting until it capture 2 of ch2-finished-signals
<- ch2
<- ch2
// usually we don't need the exact values of ch2-signals,
// so we assign it to nothing
}
func generator(ch1 chan SomeType1, ch2 chan SomeType2) {
for (YOUR_CONDITION){
// generate something
//....
// send to channel
ch1 <- someValueOfType1
}
ch1 <- magicStopValue
ch2 <- weAreFinishedSignal1
}
func processor(ch1 chan SomeType1, ch2 chan SomeType2) {
// "read" value from ch1
value := <-ch1
for value != magicStopValue {
// make some processing
// ....
//get next value from ch1 and replay processing
value = <- ch1
}
// here we can send signal that goroutine2 is finished
ch2 <- weAreFinishedSignal2
}
如果 goroutines 在一個線程中,它們的通信速度會更快。對我來說,通道性能差得很遠,但足以滿足多種用途。
- 1 回答
- 0 關注
- 223 瀏覽
添加回答
舉報