Go Concurrent Part.1 (基礎 channel & select)

開始玩 Go Concurrent 部分,最好還是先 channel & select 先弄清楚點。

Channel

初始狀況為 nil

Channel Type

可以設定為 send only receive only & 雙向

1
2
3
chan T          // 雙向
chan<- float64 // send only
<-chan int // receive only

特殊狀況一 nil channel

對一個 nil channel 傳送接收會照成永久 block

1
2
<- nilCH
nilCH <-

特殊狀況二 closed channel

closed channel 傳送資料會造成 run-time Panic

send data to closed channel
1
closedCh <- 1 // run-time Panic

closed channel 接收資料會得到 zero value

receive data from closed channellink
1
2
3
4
5
6
7
8
9
10
11
12
13
package main

import "fmt"

func main() {
a := make(chan int,3)
a <- 1
a <- 2
close(a)
fmt.Println(<-a) // 1
fmt.Println(<-a) // 2
fmt.Println(<-a) // 0
}

select

  1. For all the cases in the statement,
    the channel operands of receive operations and the channel and right-hand-side expressions of send statements are evaluated exactly once,
    in source order, upon entering the “select” statement.

  2. 如果有一個以上的 communications 可以執行,則隨機取一
    如果沒有可以執行的 communication,但有 default,則選 default
    如果連 default 都沒有的話,select 會等到其中一個 communication 可以執行

  3. def
  4. 如果選了接收的 case,左手方會被賦值
  5. The statement list of the selected case is executed.

select 只有 nil channel 且沒 default 則會 block forever