我正在嘗試學習圍棋,并且正在操場上進行試驗。我有一個非常簡單的代碼。我試圖在 go 例程中同時使用 Structs 和 Slices。我不確定這是否是我會在生產中使用的東西,但它似乎有點不對勁,所以在這里:func main() { routinemsg := make(chan []Person) routinemsg2 := make(chan []Person) // create the person records p1 := newPerson("john doe", 25) p2 := newPerson("dohn joe", 52) p3 := newPerson("bohn joo", 30) // send a slice of Person to the first routine go func() { routinemsg <- []Person{p1, p2} }() // retrieve the slice from the first routine[in the append] // append p3 to the slice retrieved from the first routine // send the new slice to the second routine go func() { routinemsg2 <- append(<-routinemsg, p3) }() // I am able to see the first Println but when I insert the second one I get a deadlock error // also, same error if I use one Println with 2 arguments. fmt.Println(<-routinemsg) fmt.Println(<-routinemsg2)}我聽說過等待小組,但還不了解他們!所以,對我好點:D,謝謝你抽出時間
2 回答

LEATH
TA貢獻1936條經驗 獲得超7個贊
上只有一個發送操作routinemsg
,但您有 2 個接收操作:一個在已啟動的 goroutine 中,另一個在 goroutine 中main
。一個發送的值只能被一個接收者接收一次。
如果啟動的 goroutine 從routinemsg
first 接收,那么這將是一個死鎖:接收將main
永遠阻塞。
如果main
goroutine 將首先接收,那么啟動的 goroutine 將永遠阻塞(試圖從它接收),因此它永遠不會發送任何東西 on ,因此來自inroutinemsg2
的接收也將永遠阻塞:再次死鎖。routinemsg2
main
刪除fmt.Println(<-routinemsg)
中的行main()
,然后最終接收 fromroutinemsg2
可以(最終)繼續并打印包含p1
,p2
和 的切片p3
:
[{john doe 25} {dohn joe 52} {bohn joo 30}]
在Go Playground上嘗試一下。

慕斯王
TA貢獻1864條經驗 獲得超2個贊
如果您使用如下所示的緩沖通道,
buffered := make(chan string, 2) buffered <- "1" buffered <- "2" fmt.Println(<-buffered) fmt.Println(<-buffered)
您可以從同一通道多次發送和接收值。
但是,您仍然可以通過傳遞給make 的參數來限制發送和接收的次數!此外,對于緩沖通道,您將始終按照發送到通道的順序接收值。
因此,您從第二個接收器收到的第二個值將始終是發送到通道的第二個值。
- 2 回答
- 0 關注
- 130 瀏覽
添加回答
舉報
0/150
提交
取消