Skip to content

Instantly share code, notes, and snippets.

@huahuayu
Created January 23, 2019 06:12
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 huahuayu/110a3a5a895f86565fa842ccc7237681 to your computer and use it in GitHub Desktop.
Save huahuayu/110a3a5a895f86565fa842ccc7237681 to your computer and use it in GitHub Desktop.
[bufferedchannel]bufferedchannel with waiting group #waiting group #channel
package main
import (
"gpool"
"fmt"
"net/http"
"time"
)
func main() {
links := []string{
"http://baidu.com",
"http://qq.com",
"http://taobao.com",
"http://jd.com",
"http://z.cn",
}
pool := gpool.New(5)
for{
for _,l := range links {
pool.Add(1)
go func(link string) {
checkLink(link)
time.Sleep(time.Second)
pool.Done()
}(l)
}
}
pool.Wait()
}
func checkLink(link string) {
_, err := http.Get(link)
if err != nil {
fmt.Println(link, "might be down!")
return
}
fmt.Println(link, "is up!")
}
package gpool
import (
"sync"
)
type pool struct {
queue chan int
wg *sync.WaitGroup
}
func New(size int) *pool {
if size <= 0 {
size = 1
}
return &pool{
queue: make(chan int, size),
wg: &sync.WaitGroup{},
}
}
func (p *pool) Add(delta int) {
for i := 0; i < delta; i++ {
p.queue <- 1
}
for i := 0; i > delta; i-- {
<-p.queue
}
p.wg.Add(delta)
}
func (p *pool) Done() {
<-p.queue
p.wg.Done()
}
func (p *pool) Wait() {
p.wg.Wait()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment