douao8204 2016-06-05 19:24
浏览 64
已采纳

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

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

I am trying to figure out how I can test my background function where there can be random io.EOF in a stream using a bytes.Buffer?

Example:

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
", 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]))
    }
}

The result I am looking for is:

1)teststring
2)teststring
3)teststring
4)teststring
5)teststring

How can I achieve this using time.Sleep(1 * time.Second) to simulate latency?

  • 写回答

1条回答 默认 最新

  • dqz7636 2016-06-05 20:03
    关注

    Are you sure you want to use bytes.Buffer? It is not a stream and it is not thread safe, thats why you get race condition. Use io.Pipe().

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

    package main
    
    import (
        "fmt"
        "io"
        "time"
    )
    
    func main() {
        pr, pw := io.Pipe()
        go background(pr)
        i := 0
        for i < 5 {
            i++
            fmt.Fprintf(pw, "%d)teststring
    ", i)
            time.Sleep(1 * time.Second)
    
        }
        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
            }
            fmt.Print(string(buf[:n]))
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 求解决扩散模型代码问题
  • ¥15 工创大赛太阳能电动车项目零基础要学什么
  • ¥20 limma多组间分析最终p值只有一个
  • ¥15 nopCommerce开发问题
  • ¥15 torch.multiprocessing.spawn.ProcessExitedException: process 1 terminated with signal SIGKILL
  • ¥15 QuartusⅡ15.0编译项目后,output_files中的.jdi、.sld、.sof不更新怎么解决
  • ¥15 pycharm输出和导师的一样,但是标红
  • ¥15 想问问富文本拿到的html怎么转成docx的
  • ¥15 我看了您的文章,遇到了个问题。
  • ¥15 GitHubssh虚拟机连接不上