-1
我收到了URL的标准线,如: $ echo -e'https://golang.org \ nhttps://godoc.org \ nhttps://golang.org'|去运行1.go。 的任务是从每个单词“Go”的WEB页码中获取。但我不允许启动超过5个够程,可以只使用标准库 这里是我的代码:如何正确限制门廊的数量
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 ...
很明显,额外的穴居已经开始。如何解决它?可能有更方便的方法来限制goroutines的数量?
你为什么试图限制够程,以及为什么你认为这是个问题?你自己开始5,这是你需要控制的全部。 – JimB
@JimB不超过5个goroutines - 这是一项任务 – Fricazoed
但是你正在发出http请求,如果不启动goroutine就无法完成,并且运行时需要一些工作。更不用说goroutine id与多少实际运行无关,goroutines在时间内被创建和销毁。 – JimB