2021-03-11: Go, coroutines inside again, they don’t matter, right? When the external coroutine crashes, will the internal coroutine still execute? How do I make the inner coroutine stop when the outer coroutine finishes? Golang native package, let the internal coroutine stop running, how to achieve? 1. External coroutines have nothing to do with internal coroutines. 2. If the program does not crash, the execution of the internal coroutine will not be affected. If nothing special is done, the whole program will crash. 3. Three ways: sharing variables as flag bits, channels, and context. All three are cooperative interrupts, not preemption. For programmers, preemptive interrupts are impossible.

If you can achieve preemption, please send the code, thank you.

The code is written in Golang, and the code is as follows:

package main

import (
    "context"
    "fmt"
    "time"
)

func main(a) {
    input := 0
    for {
        fmt.Println("1. Flag bit Mode")
        fmt.Println("2. Access Mode")
        fmt.Println("3. Context mode")
        fmt.Println("4. Quit")
        fmt.Println("Please enter a number:")
        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. The sign bit
func outer1(a) {
    isInterrupt := false
    inner := func(a) {
        for {

            if isInterrupt {
                fmt.Println("Inner1 exit")
                break
            } else {
                fmt.Println("Inner1 executing...")
                time.Sleep(time.Second * 1)}}}go inner()
    fmt.Println("Outer1 waiting... 5s")
    time.Sleep(time.Second * 5)
    isInterrupt = true
    fmt.Println("Outer1 exit")}/ / 2. Channel
func outer2(a) {
    c := make(chan struct{}, 1)
    inner2 := func(a) {
        for {
            select {
            case <-c:
                fmt.Println("Inner2 exit...")
                return
            default:
                fmt.Println("Inner2 executing...")
                time.Sleep(time.Second * 1)}}}go inner2()
    fmt.Println("Outer2 waiting... 5s")
    time.Sleep(time.Second * 5)
    c <- struct{}{}
    fmt.Println("Outer2 exit")}//3.context
func outer3(a) {
    ctx, cancel := context.WithCancel(context.Background())
    inner3 := func(a) {
        for {
            select {
            case <-ctx.Done():
                fmt.Println("Inner3 exit...")
                return
            default:
                fmt.Println("Inner3 executing...")
                time.Sleep(time.Second * 1)}}}go inner3()
    fmt.Println("Outer3 Waiting... 5s")
    time.Sleep(time.Second * 5)
    / / operation
    cancel()
    fmt.Println("Outer3 exit")}Copy the code

The result is as follows:


Zhihu answer comment