// _Closing_ a channel indicates that no more values
// will be sent on it. This can be useful to communicate
// completion to the channel's receivers.
package main
import "fmt"
// In this example we'll use a `jobs` channel to
// communicate work to be done from the `main()` goroutine
// to a worker goroutine. When we have no more jobs for
// the worker we'll `close` the `jobs` channel.
func main() {
jobs := make(chan int, 5)
done := make(chan bool)
// Here's the worker goroutine. It repeatedly receives
// from `jobs` with `j, more := <-jobs`. In this
// special 2-value form of receive, the `more` value
// will be `false` if `jobs` has been `close`d and all
// values in the channel have already been received.
// We use this to notify on `done` when we've worked
// all our jobs.
for i := 1; i <= 3; i++ {
go func() {
for {
j, more := <-jobs
if more {
fmt.Println("received job", j)
} else {
fmt.Println("received all jobs")
done <- true
return
}
}
}()
}
// This sends 3 jobs to the worker over the `jobs`
// channel, then closes it.
j := 0
for {
j++
jobs <- j
fmt.Println("sent job", j)
}
close(jobs)
fmt.Println("sent all jobs")
// We await the worker using the
// [synchronization](channel-synchronization) approach
// we saw earlier.
<-done
}
https://play.golang.org/p/x28R_g8ftSGO程序停留在循環
我想要做的就是從分頁URL端點所有響應。作業是存儲頁碼的渠道。我有一個功能,如果更多{}檢查空響應,我有
done <- true
return
我認爲這將關閉去例行。 但是,頁面生成器for{j++; jobs <- j}
正在導致它陷入循環。任何想法如何解決這個問題?
在什麼時候,你會想到的是循環退出?它沒有條件也沒有休息,因此它將永遠運行。 – Adrian
@ scott-stensland,編輯不正確。由於我有無限的while循環,所以代碼永遠不會達到「done < - true return」。我希望能打破循環,因爲我需要保持調用url直到沒有更多記錄返回。 – lmln
@adrian,我希望打破循環,如果更多{},因爲我需要保持調用的網址,直到沒有更多的記錄返回。 – lmln