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 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?