Jau*_*u L -2 concurrency http go
我正在尝试处理包含200个URL的文件,并使用每个URL发出HTTP请求.我需要每次最多同时处理10个URL(代码应该阻塞,直到10个URL完成处理).试图解决它,但我继续创建处理200个并发连接的整个文件.
for scanner.Scan() { // loop through each url in the file
// send each url to golang HTTPrequest
go HTTPrequest(scanner.Text(), channel, &wg)
}
fmt.Println(<-channel)
wg.Wait()
Run Code Online (Sandbox Code Playgroud)
我该怎么办?
从a读取的10个例行程序池channel应该满足您的要求.
work := make(chan string)
// get original 200 urls
var urlsToProcess []string = seedUrls()
// startup pool of 10 go routines and read urls from work channel
for i := 0; i<=10; i++ {
go func(w chan string) {
url := <-w
}(work)
}
// write urls to the work channel, blocking until a worker goroutine
// is able to start work
for _, url := range urlsToProcess {
work <- url
}
Run Code Online (Sandbox Code Playgroud)
清理和请求结果留给您练习.Go通道将被阻塞,直到其中一个工作程序能够读取.