go 通道的阻塞測試

2021-09-12 23:41:40 字數 3319 閱讀 8817

go version go1.11.2 linux/amd64

package main

import "fmt"

func main()

fmt.println("naturals close ")

close(naturals)

}()go func()

fmt.println("squares close ")

close(squares)

}()for x:=range squares

}

naturals start  0

naturals end 0

naturals start 1

squares start 0

squares end 0

squares start 1

naturals end 1

naturals start 2

main 0

main 1

squares end 1

squares start 2

squares end 2

main 2

naturals end 2

naturals start 3

naturals end 3

naturals start 4

squares start 3

squares end 3

squares start 4

naturals end 4

naturals start 5

main 3

main 4

squares end 4

squares start 5

squares end 5

main 5

naturals end 5

naturals start 6

naturals end 6

naturals start 7

squares start 6

squares end 6

squares start 7

naturals end 7

naturals start 8

main 6

main 7

squares end 7

squares start 8

squares end 8

main 8

naturals end 8

naturals start 9

naturals end 9

naturals close

squares start 9

squares end 9

squares close

main 9

重點是開頭的

naturals start  0

naturals end 0

naturals start 1

squares start 0

無緩衝通道可以塞進乙個資訊,然後繼續往下走,

如果這個資訊還沒有接收,繼續傳送訊息,則會造成阻塞,會切換到另外乙個goroutine

package main

import "fmt"

func main()

fmt.println("naturals close ")

close(naturals)

}()go func()

fmt.println("squares close ")

close(squares)

}()for x:=range squares

}

naturals start  0

naturals end 0

naturals start 1

naturals end 1

naturals start 2

squares start 0

squares end 0

squares start 1

naturals end 2

naturals start 3

main 0

main 1

squares end 1

squares start 2

squares end 2

squares start 3

main 2

main 3

squares end 3

naturals end 3

naturals start 4

naturals end 4

naturals start 5

naturals end 5

naturals start 6

squares start 4

squares end 4

squares start 5

naturals end 6

naturals start 7

main 4

main 5

squares end 5

squares start 6

squares end 6

squares start 7

main 6

main 7

squares end 7

naturals end 7

naturals start 8

naturals end 8

naturals start 9

naturals end 9

naturals close

squares start 8

squares end 8

squares start 9

main 8

main 9

squares end 9

squares close

重點是開頭的

naturals start  0

naturals end 0

naturals start 1

naturals end 1

naturals start 2

squares start 0

容量為1的有緩衝通道可以塞進2個資訊,然後繼續往下走,

如果這2個資訊還沒有接收,繼續傳送訊息,則會造成阻塞,會切換到另外乙個goroutine

go 非阻塞通道

預設情況 channel 傳送和接收資料時阻塞的 然而我們可以使用select的default的選項來實現無阻塞傳送和接收資料 甚至可以將多個select的case選項和default選項結合起來使用 package main import fmt func main 如果case阻塞 則執行def...

go 通道 go語言通道channel

通過使用通道,在多個goroutine傳送和接受共享的資料,達到資料同步的目的。通道,他有點像在兩個routine之間架設的管道,乙個goroutine可以往這個管道裡塞資料,另外乙個可以從這個管道裡取資料,有點類似於我們說的佇列。宣告乙個通道很簡單,我們使用chan關鍵字即可,除此之外,還要指定通...

Go 中的通道

從底層實現上來看,通道只是乙個佇列。同步模式下,傳送和接收雙方配對,然後直接複製資料給對方。如配對失敗,則置入等待佇列,直到另一方出現後才會喚醒。非同步模式搶奪的則是資料緩衝槽。傳送方要求有空槽可供寫入,而接收方則要求有緩衝資料可讀。需求不符時,同樣加入等待佇列,直到有另一方寫入資料或騰出空槽後被喚...