我需要定期刷新频道的内容。我用 len() 做到了这一点,我想知道是否有更好的方法来做到这一点。
http://play.golang.org/p/YzaI_2c_-F
package main
import (
"fmt"
"math/rand"
"time"
)
func main() {
commch := make(chan int, 100)
go fillchan(commch)
drainchan(commch)
}
func fillchan(commch chan int) {
for {
select {
case <-time.Tick(30 * time.Millisecond):
commch <- rand.Int()
}
}
}
func drainchan(commch chan int) {
for {
chanlen := len(commch) // get number of entries in channel
time.Sleep(1 * time.Second)
for i := 0; i <= chanlen; i++ { //flush them based on chanlen
fmt.Printf("chan len: %s num: %s\n", chanlen, <-commch)
}
}
}
编辑 1:似乎这是这样做的更好方法 http://play.golang.org/p/4Kp8VwO4yl
package main
import (
"fmt"
"math/rand"
"time"
)
func main() {
commch := make(chan int, 1000)
go fillchan(commch)
for {
select {
case <-time.Tick(1000 * time.Millisecond):
drainchan(commch)
}
}
}
func fillchan(commch chan int) {
for {
select {
case <-time.Tick(300 * time.Millisecond):
commch <- rand.Int()
}
}
}
func drainchan(commch chan int) {
for {
select {
case e := <-commch:
fmt.Printf("%s\n",e)
default:
return
}
}
}
编辑 2:删除选择,防止内存泄漏随着时间的推移。滴答 http://play.golang.org/p/WybAhRE3u4
package main
import (
"fmt"
"math/rand"
"time"
)
func main() {
commch := make(chan int, 1000)
go fillchan(commch)
for _ = range time.Tick(1000 * time.Millisecond) {
drainchan(commch)
}
}
func fillchan(commch chan int) {
for _ = range time.Tick(300 * time.Millisecond) {
commch <- rand.Int()
}
}
func drainchan(commch chan int) {
for {
select {
case e := <-commch:
fmt.Printf("%s\n", e)
default:
return
}
}
}
冉冉说
阿晨1998
相关分类