简体   繁体   中英

Golang channel blocking operations

I'm trying to stop child (or chained) go channels, but operation is blocking (eg listener with wait.network connection)

Because operation is blocking, for and case never enter in case <-quit

How to solve this?

package main

import (
    "fmt"
    "time"
)

func main() {
    quit := make(chan bool)

    fmt.Println("Starting Channel 001")
    go func() {
        for {
            select {
            case <-quit:
                fmt.Println("Channel 001 stopped")
                // Expected result: hangFunction stop execution looping
                return
            default:
                hangFunction()
                time.Sleep(1 * time.Second)

            }
        }
    }()

    time.Sleep(2 * time.Second)

    fmt.Println("Closing channel 001")
    close(quit)

    time.Sleep(1 * time.Hour)
}

func hangFunction() {
    for {
        fmt.Println("[hangFunction] Looping")
        time.Sleep(1 * time.Second)
    }
}

You can remove the for{} loop in hangFunction() which is blocking forever:

func hangFunction() {
    fmt.Println("[hangFunction] Looping")
    time.Sleep(1 * time.Second)
}

Or you can monitor the channel from within the function as @Adrian mentionned in the comments, by doing something like:

func hangFunction(quit chan bool) {
    for {
        select {
        case <-quit:
            return
        default:
            fmt.Println("[hangFunction] Looping")
            time.Sleep(1 * time.Second)
        }
    }
}

which is not ideal as you have the same select{} block twice (in your main and in the function). It will work tho.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM