1. 程式人生 > >Go Example--關閉通道

Go Example--關閉通道

done ret close class sent true jobs print val

package main

import (
    "fmt"
)

func main() {
    jobs := make(chan int, 5)
    done := make(chan bool)

    go func() {
        for {
            //讀取通道方式, val,ok := <-chan 通道關閉後,ok是false
            j, more := <-jobs
            if more {
                fmt.Println("received job", j)
            } else {
                fmt.Println("received all jobs")
                done <- true
                return
            }
        }
    }()

    for j := 1; j <= 3; j++ {
        jobs <- j
        fmt.Println("sent job", j)
    }
    //關閉通道
    close(jobs)
    fmt.Println("sent all jobs")
    <-done
}

Go Example--關閉通道