[英]Golang race condition when sharing channel across parallel goroutines
[英]How channel buffers work in golang when used without goroutines (within their scope) vs when they are passed to goroutines?
我絕對是Golang的新手。 我正在通過環游學習,然后以自己的理解實施想法。 我在使用goroutines時遇到問題。 我創建了一個無緩沖的通道,然后向該通道發送了一個字符串。
func main() {
p := make(chan string)
p <- "Hello goroutine"
fmt.Println(<-p)
}
引發錯誤
致命錯誤:所有goroutine都在睡着-死鎖!
我明白了,通道是無緩沖的。 ( 這就是原因。對嗎? )。
但是當我將p <- "Hello goroutine
重構為goroutine時
func main() {
p := make(chan string)
go sendHello(p)
fmt.Println(<-p)
}
func sendHello(p chan string) {
p <- "Hello goroutine"
}
它沒有問題。 我讀到,在大多數情況下,我們不需要在映射,切片和通道中使用指針來修改值。 channel p
通過具有單獨緩沖區的副本傳遞給func sendHello(p chan string)
。 我仍然無法擺脫困境。
請記住,通道具有兩端,即發送方和接收方 。 您的問題與執行順序有關。
在第一個示例中,當您使用無緩沖通道時,該通道期望接收器 ,而在發送Hello goroutine
消息時一直沒有接收器 ,並等待直到有一個接收器為止(緩沖通道不是這種情況,因為它不需要等待),執行將永遠不會到達下一行(即死鎖)。
但是在第二個示例中,接收者綁定到通道,並且在之后執行常規程序,並且發送者和接收者都不會保持等待狀態。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.