Skip to content

Instantly share code, notes, and snippets.

@drtaka
Last active February 10, 2020 11:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save drtaka/c821a8bf02b35a4a6175edd7da4d559e to your computer and use it in GitHub Desktop.
Save drtaka/c821a8bf02b35a4a6175edd7da4d559e to your computer and use it in GitHub Desktop.
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