Skip to content

Instantly share code, notes, and snippets.

@mix3
Created July 17, 2014 09:25
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 mix3/093f081e2265d5f33e81 to your computer and use it in GitHub Desktop.
Save mix3/093f081e2265d5f33e81 to your computer and use it in GitHub Desktop.
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