go - bufio.NewScanner 的重置方法?
问题描述
有没有办法重置 *Scanner(来自 bufio.NewScanner)或清除旧令牌?不幸的是,“func (b *Reader) Reset(r io.Reader)”不适用于 *Scanner。
更新/澄清: 我想在“time.Sleep(30 * time.Second)”结束时使用 os.Stdout 中的最新数据继续,并跳过这 30 秒内可以读取的所有数据。
我目前正在使用 for 循环作为肮脏的解决方法:
scanner := bufio.NewScanner(os.Stdout)
for scanner.Scan() {
fmt.Println(scanner.Text())
if scanner.Text() == "abc" {
//do something that takes a little time
time.Sleep(30 * time.Second)
// my dirty workaround:
// skips all old tokens/inputs
for skip := time.Now(); time.Since(skip).Seconds() < 10; {
scanner.Scan()
}
}
}
解决方案
在 goroutine 中运行 long 操作。在 goroutine 运行时丢弃输入。
scanner := bufio.NewScanner(os.Stdout)
var discard int32
var wg sync.WaitGroup
for scanner.Scan() {
if atomic.LoadInt32(&discard) != 0 {
continue
}
fmt.Println(scanner.Text())
if scanner.Text() == "abc" {
atomic.StoreInt32(&discard, 1)
wg.Add(1)
go func() {
defer wg.Done()
defer atomic.StoreInt32(&discard, 0)
//do something that takes a little time
time.Sleep(30 * time.Second)
}()
}
}
wg.Wait() // wait for long process after EOF or error.
推荐阅读
- gcc - AERMOD 安装错误,使用自制软件和 gfortran
- facebook - web google auth 在 facebook 浏览器和 Messenger 中不起作用
- postgresql - 如何从云运行中的容器连接到 gcloud postgres db
- haskell - 如何使用镜头实现 unsafePartsOf
- php - 我的数据库只能添加一个订单信息
- javascript - 当数据值为 0 时,Django Chartjs 输出“无数据”
- javascript - React Redux:无法读取未定义的属性“道具”
- java - eclipse中的资源泄漏警告和断点
- java - 如何通过 Zuul2 配置反向代理?
- amazon-web-services - S3 性能最佳实践