doupinge9055 2019-03-26 05:34 采纳率: 100%
浏览 316

为什么在for循环中调用ioutil.ReadFile()后会挂起?

I wrote a function that converts an image to a base64 string:

func getBase64Screenshot() string {
    // Image name
    imageName := "Screenshots/screenshot.png"

    imageFileBytes, err := ioutil.ReadFile(imageName)
    handleError(err)

    // Converts file to base64 string
    encoded := base64.StdEncoding.EncodeToString(imageFileBytes)

    return encoded
}

The above function is called in a for loop, however after some iterations of the for loop, the program just hangs at the line imageFileBytes, err := ioutil.ReadFile(imageName) (it doesn't throw an error, it just stops running and stalls).

I ran some experiments and found that if I used a smaller image, it would make it through ~5 iterations of the for loop before stalling, however if I screenshot my entire screen it would only make it through the first iteration of the for loop before stalling.

My question is this: What is causing the program to hang, and is there anything I can do to prevent it from hanging?

Thanks!

  • 写回答

3条回答 默认 最新

  • doulanli6146 2019-03-26 05:44
    关注

    Debug your code.


    Try this and let me know if this works for you too:
    This works like a charm for me on Linux:

    package main
    
    import (
        "encoding/base64"
        "fmt"
        "io/ioutil"
        "log"
        "os"
    )
    
    func main() {
        for i := 0; i < 10; i++ {
            fmt.Println(getBase64Screenshot()[:10])
        }
    }
    func getBase64Screenshot() string {
        buf, err := ioutil.ReadFile(os.Args[0])
        if err != nil {
            log.Fatal(err)
        }
        encoded := base64.StdEncoding.EncodeToString(buf)
        return encoded
    }
    

    Output:

    time go run main.go
    f0VMRgIBAQ
    f0VMRgIBAQ
    f0VMRgIBAQ
    f0VMRgIBAQ
    f0VMRgIBAQ
    f0VMRgIBAQ
    f0VMRgIBAQ
    f0VMRgIBAQ
    f0VMRgIBAQ
    f0VMRgIBAQ
    
    real    0m0.340s
    user    0m0.369s
    sys     0m0.128s
    
    评论

报告相同问题?

悬赏问题

  • ¥15 使用C#,asp.net读取Excel文件并保存到Oracle数据库
  • ¥15 C# datagridview 单元格显示进度及值
  • ¥15 thinkphp6配合social login单点登录问题
  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配