duanchuan6350 2017-04-27 12:08
浏览 183

如何正确限制goroutine的数量

I'm getting in 'stdin' lines of URL's like: $ echo -e 'https://golang.org https://godoc.org https://golang.org' | go run 1.go . The task is to get from each WEB-page number of word "Go". But I'm not allowed to start more than 5 goroutines and can use only standard library Here is my code:

    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) );
}

I thought it works until I passed more than 5 URL (one of them was incorrect) to stdin. The output was:

 goroutine 9 [running]:
 panic ...

Obviously, extra goroutnes have been started. How to fix it? May be there are more convenient way to limit number of goroutines?

  • 写回答

1条回答 默认 最新

  • douqiao3453 2017-04-27 12:42
    关注

    goroutine 9 [running]:

    Some goroutines are started by the runtime, and by web fetches.

    Looking at your code, you only started 5 goroutines.

    If you really want to know how many go routines you are running use runtime.Numgoroutine

    评论

报告相同问题?

悬赏问题

  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)
  • ¥15 AIC3204的示例代码有吗,想用AIC3204测量血氧,找不到相关的代码。
  • ¥20 CST怎么把天线放在座椅环境中并仿真
  • ¥15 任务A:大数据平台搭建(容器环境)怎么做呢?