GO程序陷入循环

标签 go

// _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_g8ftS

我正在尝试做的是从分页 url 端点获取所有响应。 jobs 是一个存储页码的 channel 。我有一个函数 if more{} 检查空响应,我有

done <- true
return

我认为这会关闭 go 例程。 但是,页面生成器 for{j++; jobs <- j}导致它陷入循环。知道如何解决这个问题吗?

最佳答案

根据定义,没有条件的 for 循环是无限循环。除非你加入一些逻辑来打破这个无限循环,否则你永远无法摆脱它。

在您的 playground 中,您的评论暗示您要发送 3 个作业。您应该相应地更改 for 循环:

for j := 0; j < 3; j++ {
  jobs <- j
  fmt.Println("sent job", j)
}

关于GO程序陷入循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46187181/

相关文章:

mysql - 在 mysql 中使用 gorm 插入类型 []byte 引发 "Error 1241: Operand should contain 1 columns(s)"

go - 来自 Goroutine channel 的随机结果,该 channel 接收指向底层对象的指针

hash - Go:这个散列函数的范围如何从 0-32 位?

json - 如何使用 Go 漂亮地打印 JSON?

git - 无法从 git 获取对 git post-update Hook 的依赖

mongodb - Mongo-go-driver error New client error ClientOptions in argument to mongo.NewClient 错误

json - 在 Go 中将组合对象转换为 json

forms - Golang - 解析形式;错误 = mime : expected slash after first token

html - Golang & Martini 代码块

go - 从 SQL QueryRow 结果动态生成结构字段