填补缓冲的陈,直到获得满或持续时间过去 [英] filling a buffered chan until gets full or a time duration passes
本文介绍了填补缓冲的陈,直到获得满或持续时间过去的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个缓冲的 chan字符串
,我一直用随机字符串填充它,直到时间消逝或直到它满了。
我的问题是,我是否应该使用股票代码来考虑它的一次性任务,或者是否有更方便的方法?
这里是是我目前的做法
package main
import(
fmt
time
)
func main(){
res:= fillChan(time.Duration(1 * time.Nanosecond),100000)
$ bc:= make(chan string,chanSize)
ticker:= time.NewTicker(maxDuration)
为{
select {
case< -ticker.C:
ticker .Stop()
返回c
case c< - 随机消息:
默认值:
返回c
}
}
}我不是Go的专家(其实,我不是专家,我从来没有使用它),但文档建议 Timer
或
for single events。
select {
case< -time.After(1 * time.Nanosecond) :
return c
case c < - Random message:
default:
return c
}
i have a chan string
which is buffered, i keep filling it with random strings until a time.Duration passes or until it gets full.
my question is should i use a ticker for that considering that its a one time task or is there a more convienient way?
here is my current way of doing it
package main
import (
"fmt"
"time"
)
func main() {
res := fillChan(time.Duration(1*time.Nanosecond), 100000)
fmt.Println(len(res))
}
func fillChan(maxDuration time.Duration, chanSize int) chan string {
c := make(chan string, chanSize)
ticker := time.NewTicker(maxDuration)
for {
select {
case <-ticker.C:
ticker.Stop()
return c
case c <- "Random message":
default:
return c
}
}
}
解决方案 I am no expert in Go (in fact, I've never used it), but the documentation suggests Timer
, or After
for single events.
select {
case <-time.After(1*time.Nanosecond):
return c
case c <- "Random message":
default:
return c
}
这篇关于填补缓冲的陈,直到获得满或持续时间过去的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文