Go: 協程的生命週期管理

協程的生命週期:

1. 定義:

協程的創建等全部生命歷程的管理。通俗的講就是“保姆”。

它的作用是便於協程的回收利用。

goroutine申請的代價很小,但是在go程序中,goroutine的總量是有上限,超過上限,多餘出來的協程就得等到前面的協程完成任務後能開始運行。所以適時的進行回收。

2. 生命週期分類:

  • 協程創建
  • 協程回收: 由Go語言的GC和垃圾回收機制控制的
  • 協程中斷: 通過context包實現

3. 如何實現:

  • context實現中斷

 

package main

import (
	"context"
	"fmt"
	"sync"
)

func main() {
	// 初始化一個context
	parent := context.Background()
	// 生成一個可取消的context(還有超時取消,超時取消用的比較少)
	ctx, cancel := context.WithCancel(parent)
	runTimes := 0
	var wg sync.WaitGroup
	wg.Add(1)
	go func(ctx context.Context) {
		for {
			select {
			case <- ctx.Done():
				fmt.Println("Goroutine Done!")
				return
			default:
				fmt.Printf("Goroutine Running... Times: %d\n", runTimes)
				runTimes = runTimes + 1
			}
			if runTimes > 5 {
				cancel()// 超過5次就取消
				wg.Done()
			}

		}
	}(ctx)
	wg.Wait()
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章