
今天大概閱讀了一下Golang的并行運算,以下簡要概括并行運算
go func() // 可以啟動一個協(xié)程
可以同時運行多個協(xié)程,協(xié)程之間通訊使用channel(通道)來進(jìn)行協(xié)程間通信
channel的定義如下
c := chan string
意味著這是一個string類型的通道
channel可以理解為一個隊列,先進(jìn)者先出,但是它只能占有一個元素的位置,我們可以義如下方法添加/讀取元素,<- 是一個運算符
c <- "hello" //把"hello"加入到c通道中
msg := <- c // 將c中的"hello"取出到msg里
在并行運算時我們可能需要從多個通道讀取消息,此時我們用到
for{
select{
case msg1 := channel_1:
fmt.Println(msg1)
case msg2 := channel_2:
fmt.Println(msg2)
}
}
此時如果channel_1和channel_2兩個通道都一直沒有消息,那么該協(xié)程將會被阻塞在select語句,直到channel_1或者channel_2有消息為止
那如何解決阻塞問題呢?
我們需要在select中再添加一種情況,代碼如下
for{
select{
case msg1 := <- channel_1:
fmt.Println(msg1)
case msg2 := <- channel_2:
fmt.Println(msg2)
case msg3 := <- time.After(time.second*5):
fmt.Println("get message time out, check again...")
}
}
意思是如果在select中停留5秒鐘還沒有收到channel1和channel2的消息,那么time.After(time.second*5)就會返回一個搭載了當(dāng)前時間的一個通道,此時select就能正確響應(yīng)了
看到這里博主就有點呆了
不太理解time.After()這是一個什么東西,居然能夠這么神奇地等待5秒鐘就可以返回通道
于是無奈之下只能瞅一瞅time.After的源代碼,因為是第一天學(xué)Go語言所以很多東西還是不太懂,只能看懂大概的
大概的情況是這樣的:
// 函數(shù)原型
// 文件:../time/sleep.go
func After(d Duration) <-chan Time {
return NewTimer(d).C
}
func NewTimer(d Duration) *Timer {
c := make(chan Time, 1)
t := &Timer{
C: c,
r: runtimeTimer{
when: when(d),
f: sendTime,
arg: c,
},
}
startTimer(&t.r)
return t
}
type runtimeTimer struct {
tb uintptr
i int
when int64
period int64
f func(interface{}, uintptr) // NOTE: must not be closure
arg interface{}
seq uintptr
}
以上是涉及到time.After()的函數(shù)原型,time.After()執(zhí)行的步驟是這樣子的:
- After()里直接調(diào)用NewTimer(),在NewTimer里創(chuàng)建一個Timer對象并將指針儲存在t里,通過startTimer(&t.r)傳入runtimeTimer來創(chuàng)建一個協(xié)程,這個協(xié)程會在指定的時間(5秒)后將一個Time對象送入t.C這個通道中。(runtimeTimer這里不深究)
- 將包含C(channel)和r(runtimeTimer)的t返回到After()函數(shù)的NewTimer(d)中
- After函數(shù)返回NewTimer(d).C,即After()最終返回的通道
- select此時已經(jīng)過了5秒鐘,并檢測到了這個攜帶Time對象(當(dāng)前時間)的通道的返回,便輸出“get message time out, check again...”
本文待更新....初學(xué)Golang,大佬路過請指正!