如何在 bytes.Buffer 流中处理 io.EOF?

https://play.golang.org/p/JKXKa7Pvjd


我试图弄清楚如何使用 bytes.Buffer 在流中可以有随机 io.EOF 的情况下测试我的后台函数?


例子:


package main


import (

    "fmt"

    "io"

    "bytes"

    "time"

)


func main() {

    buffer := new(bytes.Buffer)

    go background(buffer)

    i := 0

    for i < 5 {

        i++

        fmt.Fprintf(buffer, "%d)teststring\n", i)

        time.Sleep(1 * time.Second) // generates a io.EOF


    }

    time.Sleep(1 * time.Second)

}


func background(r io.Reader) {

    buf := make([]byte, 64)

    for {   

        n, err := r.Read(buf)

        if err != nil {

            fmt.Print(err.Error())

            return // removing `return` will result in race condition

        }

        fmt.Print(string(buf[:n]))

    }

}

我正在寻找的结果是:


1)teststring

2)teststring

3)teststring

4)teststring

5)teststring

如何使用time.Sleep(1 * time.Second)模拟延迟来实现这一点?


莫回无
浏览 156回答 1
1回答

慕运维8079593

您确定要使用 bytes.Buffer 吗?它不是流,也不是线程安全的,这就是你得到竞争条件的原因。使用io.Pipe()。https://play.golang.org/p/c0fLEI350wpackage mainimport (&nbsp; &nbsp; "fmt"&nbsp; &nbsp; "io"&nbsp; &nbsp; "time")func main() {&nbsp; &nbsp; pr, pw := io.Pipe()&nbsp; &nbsp; go background(pr)&nbsp; &nbsp; i := 0&nbsp; &nbsp; for i < 5 {&nbsp; &nbsp; &nbsp; &nbsp; i++&nbsp; &nbsp; &nbsp; &nbsp; fmt.Fprintf(pw, "%d)teststring\n", i)&nbsp; &nbsp; &nbsp; &nbsp; time.Sleep(1 * time.Second)&nbsp; &nbsp; }&nbsp; &nbsp; time.Sleep(1 * time.Second)}func background(r io.Reader) {&nbsp; &nbsp; buf := make([]byte, 64)&nbsp; &nbsp; for {&nbsp; &nbsp; &nbsp; &nbsp; n, err := r.Read(buf)&nbsp; &nbsp; &nbsp; &nbsp; if err != nil {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; fmt.Print(err.Error())&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; //return&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; fmt.Print(string(buf[:n]))&nbsp; &nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go