Reset method for bufio.NewScanner?

huangapple go评论77阅读模式
英文:

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() == &quot;abc&quot; {
		//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() &lt; 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(&amp;discard) != 0 {
		continue
	}

	fmt.Println(scanner.Text())

	if scanner.Text() == &quot;abc&quot; {
		atomic.StoreInt32(&amp;discard, 1)
        wg.Add(1)
		go func() {
            defer wg.Done()
			defer atomic.StoreInt32(&amp;discard, 0)
			//do something that takes a little time
			time.Sleep(30 * time.Second)
		}()
	}
}

wg.Wait() // wait for long process after EOF or error.

huangapple
  • 本文由 发表于 2021年6月23日 01:52:03
  • 转载请务必保留本文链接:https://go.coder-hub.com/68088605.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定