英文:
Reset method for bufio.NewScanner?
问题
有没有办法重置 *Scanner(来自bufio.NewScanner)或清除旧的标记?
不幸的是,"func (b *Reader) Reset(r io.Reader)" 不能与 *Scanner 一起使用。
更新/澄清:
当"time.Sleep(30 * time.Second)"结束并且在那30秒内可以读取所有数据时,我希望使用最新的数据继续。
我目前正在使用一个for循环作为临时解决方法:
scanner := bufio.NewScanner(os.Stdout)
for scanner.Scan() {
fmt.Println(scanner.Text())
if scanner.Text() == "abc" {
// 做一些需要一点时间的操作
time.Sleep(30 * time.Second)
// 我的临时解决方法:
// 跳过所有旧的标记/输入
for skip := time.Now(); time.Since(skip).Seconds() < 10; {
scanner.Scan()
}
}
}
英文:
Is there a way to reset the *Scanner (from bufio.NewScanner) or clear old tokens?
Unfortunately "func (b *Reader) Reset(r io.Reader)" does not work with *Scanner.
Update/clarification:
I want to resume with the newest data from os.Stdout when "time.Sleep(30 * time.Second)" ends and skip all data that could be read during that 30 seconds.
I am currently using a for loop as dirty workaround:
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()
}
}
}
答案1
得分: 3
在一个goroutine中运行长时间的操作。在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)
// 进行一些耗时的操作
time.Sleep(30 * time.Second)
}()
}
}
wg.Wait() // 在EOF或错误后等待长时间处理完成。
英文:
Run the long operation in a goroutine. Discard input while the goroutine is running.
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论