Created
July 17, 2014 09:25
-
-
Save mix3/093f081e2265d5f33e81 to your computer and use it in GitHub Desktop.
mutexを使いつつ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 ( | |
"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