-
Notifications
You must be signed in to change notification settings - Fork 10
/
worker_pool_http_req.go
84 lines (69 loc) · 1.36 KB
/
worker_pool_http_req.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
//
// Inspired by https://www.careercup.com/question?id=5710657300201472
// https://gobyexample.com/worker-pools
//
package main
import (
"io/ioutil"
"log"
"net/http"
"runtime"
"time"
)
const (
wikiURL = "http://en.wikipedia.org/wiki/Main_Page"
total = 100
)
func main() {
solution(runtime.NumCPU() * 2)
}
func solution(cores int) {
log.SetFlags(log.Lshortfile)
jobs := make(chan string, cores)
result := make(chan int, cores)
for w := 0; w < cores; w++ {
go worker(w, jobs, result)
}
go func() {
for ix := 0; ix < total; ix++ {
jobs <- wikiURL
}
close(jobs)
}()
for p := 1; p <= total; p++ { // total is 100 so p match with current percent
ctlen := <-result
if ctlen == 0 {
log.Println("empty response :(")
}
log.Printf("percent %d \n", p)
}
}
func main_old() {
for ix := 0; ix < total; ix++ {
hitWiki(wikiURL)
}
}
func worker(id int, jobs <-chan string, result chan<- int) {
for url := range jobs {
start := time.Now()
if cl, err := hitWiki(url); err != nil {
log.Panic(err)
} else {
result <- cl
}
log.Println("worker #", id, time.Since(start))
}
}
func hitWiki(url string) (int, error) {
client := new(http.Client)
res, err := client.Get(url)
if err != nil {
return 0, err
}
defer res.Body.Close()
bs, err := ioutil.ReadAll(res.Body)
if err != nil {
return 0, err
}
return len(bs), nil
}