Go语言(Golang)超时机制
生活随笔
收集整理的這篇文章主要介紹了
Go语言(Golang)超时机制
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
機制1:select+time.After
通過select+time.After方法實現超時機制,示例代碼如下:
package mainimport ("context""fmt""runtime""time" )func main() {timeout1()println("Goroutine數量:",runtime.NumGoroutine())time.Sleep(time.Second*10)println("Goroutine數量:",runtime.NumGoroutine()) }func timeout1() {//通過select+time.After方法實現超時機制ch := make(chan struct{}, 1)go func() {//具體業務邏輯time.Sleep(time.Second*3)ch <- struct{}{}}()select {case <-ch:fmt.Println("業務邏輯執行完成!")case <-time.After(time.Second * 2):fmt.Println("超時...")}return }運行效果
分析:上述代碼,超時時間到,執行case <-time.After(time.Second * 2),timeout1()函數退出。而
Goroutine需要等到時間到了,執行ch <- struct{}{}之后才能結束。因此在main中輸出的Goroutine分別為2(包括一個主線程)、1。
特別注意:如果將
ch := make(chan struct{}, 1)改為:
ch := make(chan struct{})若發生超時,由于timeout1()函數退出已經退出,Goroutine中的ch將一直無法寫入數據,因此該Goroutine將一直無法退出(內存泄露,有的時候也說成Goroutine泄露)。
上述代碼中寫入channel的數據為:struct{},主要作用是為了節省內存。
func main() {testSize() }func testSize() {a := 1b := truec := "1"d := struct{}{}sizeofa := unsafe.Sizeof(a)sizeofb := unsafe.Sizeof(b)sizeofc := unsafe.Sizeof(c)sizeofd := unsafe.Sizeof(d)fmt.Println(sizeofa, sizeofb, sizeofc, sizeofd) }?即:struct{} 大小為0.
?機制2:select+context
通過select+context方法實現超時機制,示例代碼如下:
package mainimport ("context""fmt""runtime""time" )func main() {timeout2(context.Background())println("Goroutine數量:",runtime.NumGoroutine())time.Sleep(time.Second*10)println("Goroutine數量:",runtime.NumGoroutine()) }func timeout2(ctx context.Context) {c, cancelFunc := context.WithTimeout(ctx, time.Second*5)go func() {//具體業務邏輯time.Sleep(time.Second*6)defer cancelFunc() //業務邏輯執行完之后,直接調用context結束}()select {//如果時間到,變量c(類型為:context)會自動調用。如果業務執行完成,cancelFunc()也會調用case <-c.Done():fmt.Println("執行結束")}return }運行效果
代碼分析:與機制1的相似,業務超時完成時,timeout2已經退出,此時該Goroutine才退出。
總結
以上是生活随笔為你收集整理的Go语言(Golang)超时机制的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 二十年后的世界和我
- 下一篇: 2021-06-16 srm平台电子化采