Created
January 23, 2019 06:12
-
-
Save huahuayu/110a3a5a895f86565fa842ccc7237681 to your computer and use it in GitHub Desktop.
[bufferedchannel]bufferedchannel with waiting group #waiting group #channel
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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!") | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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