【问题标题】:how to correctly limit number of goroutines如何正确限制 goroutine 的数量
【发布时间】:2017-09-25 05:23:25
【问题描述】:

我正在输入 URL 的“stdin”行,例如: $ echo -e 'https://golang.org\nhttps://godoc.org\nhttps://golang.org' |去运行 1.go 。 任务是从每个 WEB 页中获取单词“Go”的编号。但是我不能启动超过 5 个 goroutine 并且只能使用标准库 这是我的代码:

    package main

    import (
      "fmt"
      "net/http"
      "bufio"
      "os"
      "regexp"
      "io/ioutil"
      "time"
    )

func worker(id int, jobs<-chan string, results chan<-int) {
  t0 := time.Now()
  for url := range jobs {
    resp, err := http.Get(url)
    if err != nil {
      fmt.Println("problem while opening url", url)
      results<-0
      //continue
    }
    defer resp.Body.Close()
    html, err := ioutil.ReadAll(resp.Body)
    if err != nil {
      continue
    }
    regExp:= regexp.MustCompile("Go")
    matches := regExp.FindAllStringIndex(string(html), -1)
    t1 := time.Now()
    fmt.Println("Count for", url, ":", len(matches), "Elapsed time:", 
t1.Sub(t0),  "works id", id)
    results<-len(matches)
  }
}

func main(){
  scanner := bufio.NewScanner(os.Stdin)
  jobs := make(chan string, 100)
  results := make(chan int, 100)
  t0 := time.Now()
  for w:= 0; w<5; w++{
    go worker(w, jobs, results)
  }
  var tasks int = 0
  res := 0
  for scanner.Scan() {
      jobs <- scanner.Text()
      tasks ++
  }
  close(jobs)
  for a := 1; a <= tasks; a++ {
    res+=<-results
  }
  close(results)
  t2 := time.Now()
  fmt.Println("Total:",res, "Elapsed total time:", t2.Sub(t0) );
}

我认为它可以工作,直到我将超过 5 个 URL(其中一个不正确)传递给标准输入。输出是:

 goroutine 9 [running]:
 panic ...

显然,额外的 gooutnes 已经启动。如何解决?可能有更方便的方法来限制 goroutine 的数量?

【问题讨论】:

  • 你为什么要限制 goroutine,为什么你认为这是个问题?您自己开始 5 个,这就是您真正需要控制的所有内容。
  • @JimB 不超过 5 个 goroutine - 这是一项任务
  • 但是您正在发出 http 请求,如果不启动 goroutines 就无法完成,并且运行时也需要一些工作。更不用说 goroutine id 与实际运行的数量无关,goroutine 一直在创建和销毁。

标签: go goroutine limiting


【解决方案1】:

goroutine 9 [运行中]:

一些 goroutines 是由运行时启动的,并且是由 web fetches 启动的。

查看您的代码,您只启动了 5 个 goroutine。

如果你真的想知道你正在运行多少个 goroutine,请使用 runtime.Numgoroutine

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-03
    相关资源
    最近更新 更多