Go实例: Closing Channels

Ophira ·
更新时间:2024-11-13
· 1926 次阅读

package main import "fmt" func main() { jobs := make(chan int, 5) done := make(chan bool) go func() { for { 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 run closing-channels.go sent job 1 received job 1 sent job 2 received job 2 sent job 3 received job 3 sent all jobs received all jobs



GO实例 GO

需要 登录 后方可回复, 如果你还没有账号请 注册新账号