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]))
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算
  • ¥15 java如何提取出pdf里的文字?