golang channel 关闭方式

golang channel 关闭方式

package main

    import (

    "fmt"

    "strconv"

)

func publishTask(c chan string, count int) {

    for i := 1; i <= count; i++ {

        taskName := "task: " + strconv.Itoa(i)

        c <- taskName //publish a new task

    }

    close(c)

}

func receiveTask(c chan string) {

    closed := false

    for {

        if closed {

            return

        }

        fmt.Println("Waiting for a new task ...")

        select {

        case v, ok := <-c:

            if !ok {

                fmt.Println("c closed!")

                closed = true

            } else {

                fmt.Println("got job :", v)

            }

        }

       }

}

func main() {

    taskChan := make(chan string)

    go publishTask(taskChan, 5)

    receiveTask(taskChan)

}

你可能感兴趣的:(golang channel 关闭方式)