淺析Go語(yǔ)言中的超時(shí)控制
前言
日常開(kāi)發(fā)中我們大概率會(huì)遇到超時(shí)控制的場(chǎng)景,比如一個(gè)批量耗時(shí)任務(wù)、網(wǎng)絡(luò)請(qǐng)求等;一個(gè)良好的超時(shí)控制可以有效的避免一些問(wèn)題(比如 goroutine 泄露、資源不釋放等)。
Timer
在 go 中實(shí)現(xiàn)超時(shí)控制的方法非常簡(jiǎn)單,首先第一種方案是 Time.After(d Duration):
func main() { fmt.Println(time.Now()) x := <-time.After(3 * time.Second) fmt.Println(x) }
output:
2021-10-27 23:06:04.304596 +0800 CST m=+0.000085653
2021-10-27 23:06:07.306311 +0800 CST m=+3.001711390
time.After() 會(huì)返回一個(gè) Channel,該 Channel 會(huì)在延時(shí) d 段時(shí)間后寫(xiě)入數(shù)據(jù)。
有了這個(gè)特性就可以實(shí)現(xiàn)一些異步控制超時(shí)的場(chǎng)景:
func main() { ch := make(chan struct{}, 1) go func() { fmt.Println("do something...") time.Sleep(4*time.Second) ch<- struct{}{} }() select { case <-ch: fmt.Println("done") case <-time.After(3*time.Second): fmt.Println("timeout") } }
這里假設(shè)有一個(gè) goroutine 在跑一個(gè)耗時(shí)任務(wù),利用 select 有一個(gè) channel 獲取到數(shù)據(jù)便退出的特性,當(dāng) goroutine 沒(méi)有在有限時(shí)間內(nèi)完成任務(wù)時(shí),主 goroutine 便會(huì)退出,也就達(dá)到了超時(shí)的目的。
output:
do something...
timeout
timer.After 取消,同時(shí) Channel 發(fā)出消息,也可以關(guān)閉通道等通知方式。
注意 Channel 最好是有大小,防止阻塞 goroutine ,導(dǎo)致泄露。
Context
第二種方案是利用 context,go 的 context 功能強(qiáng)大;
利用 context.WithTimeout() 方法會(huì)返回一個(gè)具有超時(shí)功能的上下文。
ch := make(chan string) timeout, cancel := context.WithTimeout(context.Background(), 3*time.Second) defer cancel() go func() { time.Sleep(time.Second * 4) ch <- "done" }() select { case res := <-ch: fmt.Println(res) case <-timeout.Done(): fmt.Println("timout", timeout.Err()) }
同樣的用法,context 的 Done() 函數(shù)會(huì)返回一個(gè) channel,該 channel 會(huì)在當(dāng)前工作完成或者是上下文取消生效。
timout context deadline exceeded
通過(guò) timeout.Err() 也能知道當(dāng)前 context 關(guān)閉的原因。
goroutine 傳遞 context
使用 context 還有一個(gè)好處是,可以利用其天然在多個(gè) goroutine 中傳遞的特性,讓所有傳遞了該 context 的 goroutine 同時(shí)接收到取消通知,這點(diǎn)在多 go 中應(yīng)用非常廣泛。
func main() { total := 12 var num int32 log.Println("begin") ctx, cancelFunc := context.WithTimeout(context.Background(), 3*time.Second) for i := 0; i < total; i++ { go func() { //time.Sleep(3 * time.Second) atomic.AddInt32(&num, 1) if atomic.LoadInt32(&num) == 10 { cancelFunc() } }() } for i := 0; i < 5; i++ { go func() { select { case <-ctx.Done(): log.Println("ctx1 done", ctx.Err()) } for i := 0; i < 2; i++ { go func() { select { case <-ctx.Done(): log.Println("ctx2 done", ctx.Err()) } }() } }() } time.Sleep(time.Second*5) log.Println("end", ctx.Err()) fmt.Printf("執(zhí)行完畢 %v", num) }
在以上例子中,無(wú)論 goroutine 嵌套了多少層,都是可以在 context 取消時(shí)獲得消息(當(dāng)然前提是 context 得傳遞走)
某些特殊情況需要提前取消 context 時(shí),也可以手動(dòng)調(diào)用 cancelFunc() 函數(shù)。
Gin 中的案例
Gin 提供的 Shutdown(ctx) 函數(shù)也充分使用了 context。
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() if err := srv.Shutdown(ctx); err != nil { log.Fatal("Server Shutdown:", err) } log.Println("Server exiting")
比如以上代碼便是超時(shí)等待 10s 進(jìn)行 Gin 的資源釋放,實(shí)現(xiàn)的原理也和上文的例子相同。
到此這篇關(guān)于淺析Go語(yǔ)言中的超時(shí)控制的文章就介紹到這了,更多相關(guān)go超時(shí)控制內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
記一次go語(yǔ)言使用time.Duration類型踩過(guò)的坑
本文主要介紹了記一次go語(yǔ)言使用time.Duration類型踩過(guò)的坑,文中通過(guò)示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-01-01Golang map如何生成有序的json數(shù)據(jù)詳解
最近在學(xué)習(xí)Golang,發(fā)現(xiàn)了一個(gè)問(wèn)題,覺(jué)著有必要給大家總結(jié)下,下面這篇文章主要給大家介紹了關(guān)于Golang map如何生成有序json數(shù)據(jù)的相關(guān)資料,文中通過(guò)示例代碼介紹的非常詳細(xì),需要的朋友們下面來(lái)一起看看吧。2017-07-07Go 語(yǔ)言 JSON 標(biāo)準(zhǔn)庫(kù)的使用
今天通過(guò)本文給大家介紹Go 語(yǔ)言 JSON 標(biāo)準(zhǔn)庫(kù)的使用小結(jié),包括序列化和反序列化的相關(guān)知識(shí),感興趣的朋友跟隨小編一起看看吧2021-10-10Golang定制化zap日志庫(kù)使用過(guò)程分析
Zap是我個(gè)人比較喜歡的日志庫(kù),是uber開(kāi)源的,有較好的性能,在項(xiàng)目開(kāi)發(fā)中,經(jīng)常需要把程序運(yùn)行過(guò)程中各種信息記錄下來(lái),有了詳細(xì)的日志有助于問(wèn)題排查和功能優(yōu)化,但如何選擇和使用性能好功能強(qiáng)大的日志庫(kù),這個(gè)就需要我們從多角度考慮2023-03-03