Skip to content

Instantly share code, notes, and snippets.

@mix3 mix3/chanpool.go
Created Jul 17, 2014

Embed
What would you like to do?
mutexを使いつつchannelが空かそうでないかで処理を分ける
package main
import (
"log"
"math/rand"
"sync"
"time"
)
type ChanPool struct {
pool chan interface{}
sync.Mutex
}
func NewChanPool(num int) *ChanPool {
pool := make(chan interface{}, num)
for i := 0; i < num; i++ {
pool <- struct{}{}
}
return &ChanPool{pool: pool}
}
func (cp *ChanPool) get() (interface{}, bool) {
cp.Lock()
defer cp.Unlock()
num := len(cp.pool)
log.Printf("num: %d", num)
if num == 0 {
return struct{}{}, false
}
return <-cp.pool, true
}
func (cp *ChanPool) put(s interface{}) {
cp.pool <- s
}
func (cp *ChanPool) Run(okfn, overfn func()) {
s, ok := cp.get()
defer func() {
if ok {
cp.put(s)
}
}()
if ok {
okfn()
} else {
overfn()
}
}
var sleep = []time.Duration{
time.Millisecond * 50,
time.Millisecond * 100,
time.Millisecond * 150,
}
func run(cp *ChanPool) {
cp.Run(
func() {
time.Sleep(sleep[rand.Intn(len(sleep))])
log.Print("ok")
},
func() {
log.Print("over")
},
)
}
func main() {
cp := NewChanPool(10)
for {
go run(cp)
time.Sleep(time.Millisecond * 10)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.