Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
package main
import (
"log"
"sync"
"time"
)
const (
MaxGoRoutine = 3
QueueSize = 2
)
/**
起動する Go ルーチンの数を固定とし、
空いている Go ルーチンからキューに入っている URL の処理を行ってもらう
*/
func main() {
var wg sync.WaitGroup
urls := []string{
"https://www.example.com",
"https://www.example.net",
"https://www.example.com/foo",
"https://www.example.com/bar",
"https://www.example.com/?1",
"https://www.example.com/?2",
"https://www.example.com/?3",
}
queue := make(chan string, QueueSize)
for i := 0; i < MaxGoRoutine; i++ {
wg.Add(1)
go fetch(&wg, queue, i)
}
for _, url := range urls {
queue <- url
}
close(queue)
wg.Wait()
}
func fetch(wg *sync.WaitGroup, queue chan string, i int) {
defer wg.Done()
for {
// queue が close されると more は false になる。
url, more := <-queue
if more {
log.Printf("[%d]: fetching %s\n", i, url)
time.Sleep(1 * time.Second)
} else {
log.Printf("[%d]: worker exit\n", i)
return
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment