1. 程式人生 > 實用技巧 >Go語言完整解析Go!Go!Go!(一)資料型別 之 Channel & Goroutine

Go語言完整解析Go!Go!Go!(一)資料型別 之 Channel & Goroutine

一:概述

如果說goroutine是Golang的併發體的話,那麼channel就是他們之間的通訊機制,可以讓goroutine通過channel給另一個goroutine傳送資訊

channel本身是一種資料型別,同時他還會細分是哪一種channel,這種細分表示在channel中傳送的資料的型別

wxy:望文生義,channel就是一個管道,管道本身代表著一種資料型別,同時管道中流淌的是什麼型別的資料,則又是更進一層的細分

goroutine中若有channel且阻塞了,則稱goroutine洩露,這種goroutine是不會被垃圾回收的。

channel型別原始碼

路徑:go\src\runtime
type hchan struct
{ qcount uint // total data in the queue dataqsiz uint // size of the circular queue buf unsafe.Pointer // points to an array of dataqsiz elements.由元素構成的是一塊迴圈連結串列 elemsize uint16 closed uint32 elemtype *_type // element type sendx uint // send index 傳送索引,用來標記
recvx uint // receive index recvq waitq // list of recv waiters sendq waitq // list of send waiters // lock protects all fields in hchan, as well as several fields in sudogs blocked on this channel. // Do not change another G's status while holding this lock (in particular, do not ready a G), as this can deadlock
with stack shrinking. lock mutex }
type waitq struct {
first *sudog
last *sudog
}
解析:

go\src\go\types
type Chan struct { dir ChanDir elem Type }
// A ChanDir value indicates a channel direction.
type ChanDir int

二,channel的基本資訊

1. 使用make建立。

make會建立一個底層的結構,得到的是一個對底層的"引用", 如下:

ch := make(chan int) 
ch = make(chan int) // unbuffered channel
ch = make(chan int, 0) // unbuffered channel
ch = make(chan int, 3) // buffered channel with capacity 3

特點:

1). channel的拷貝是引用的拷貝,即二者使用的是一同一個底層物件;

2).channel的零值是nil;

3).相同(底層)型別的channel可以使用==運算子做比較,具體比較的內容是底層的物件;

4).有兩種方式可以建立不帶快取的channel;

5). 可以指定channel的大小,代表這個管道中可以有幾個底層物件;

2. channel的兩個主要操作:傳送和接收

ch <- x  // a send statement 
x = <-ch // a receive expression in an assignment statement 
<-ch     // a receive statement; result is discarded

說明:

1. 傳送和接收都是使用 " <-" 來表示;

2. 根據channel所在的位置來確認是傳送還是接收:

首先,<- 符號依附於channel,傳送 還是 接收 是針對channel來操作的,即“傳送給"channel or ”接收自“channel;

然後,本著從右向左的原則,

最後,ch <- x, 代表把x的值給ch, 所以是send一個數據給ch

x = <- ch 和 <-ch, 代表將ch的值取出來, 即接收來自ch的內容賦值給在左則為承受者即

三, channel的用法