2021-03-11:go中,協程內部再啓用協程,它們是不要緊,對吧?外部協程奔潰,內部協程還會執行嗎?外部協程執行結束的時候,如何讓內部協程也中止運行?golang原生提供的包裏,讓內部協程中止運行,如何實現?
福哥答案2021-03-11:
1.外部協程和內部協程不要緊。
2.若是程序不奔潰,不會影響內部協程繼續執行。若是沒作特殊處理,整個程序會奔潰。
3.三種方式:共享變量做爲標誌位,通道,上下文context。這三種方式均是協做式中斷,不是搶佔式。對於程序員,是沒法實現搶佔式中斷的。程序員
若是能實現搶佔式,請發代碼,謝謝。golang
代碼用golang編寫,代碼以下:ide
package main import ( "context" "fmt" "time" ) func main() { input := 0 for { fmt.Println("1.標誌位方式") fmt.Println("2.通道方式") fmt.Println("3.上下文方式") fmt.Println("4.退出") fmt.Println("請輸入數字:") fmt.Scanf("%d", &input) switch input { case 1: go outer1() case 2: go outer2() case 3: go outer3() default: return } time.Sleep(time.Second * 7) } fmt.Scanf("%d", &input) } //1.標誌位 func outer1() { isInterrupt := false inner := func() { for { if isInterrupt { fmt.Println("inner1 退出") break } else { fmt.Println("inner1 執行中...") time.Sleep(time.Second * 1) } } } go inner() fmt.Println("outer1 等待中... 5s") time.Sleep(time.Second * 5) isInterrupt = true fmt.Println("outer1 退出") } //2.通道 func outer2() { c := make(chan struct{}, 1) inner2 := func() { for { select { case <-c: fmt.Println("inner2 退出...") return default: fmt.Println("inner2 執行中...") time.Sleep(time.Second * 1) } } } go inner2() fmt.Println("outer2 等待中... 5s") time.Sleep(time.Second * 5) c <- struct{}{} fmt.Println("outer2 退出") } //3.context func outer3() { ctx, cancel := context.WithCancel(context.Background()) inner3 := func() { for { select { case <-ctx.Done(): fmt.Println("inner3 退出...") return default: fmt.Println("inner3 執行中...") time.Sleep(time.Second * 1) } } } go inner3() fmt.Println("outer3 等待中... 5s") time.Sleep(time.Second * 5) //操做 cancel() fmt.Println("outer3 退出") }
執行結果以下:code