本文介绍了如何在* os.File/io中设置超时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道有一个名为 SetReadDeadline 的函数可以在套接字(conn.net)读取中设置超时,而io.Read则不可以.有一种方法可以启动另一个例程作为计时器来解决此问题,但它带来了另一个问题,即读取器例程(io.Read)仍会阻塞:

I know there is a function called SetReadDeadline that can set a timeout in socket(conn.net) reading, while io.Read not. There is a way that starts another routine as a timer to solve this problem, but it brings another problem that the reader routine(io.Read) still block:

func (self *TimeoutReader) Read(buf []byte) (n int, err error) { 
    ch := make(chan bool) 
    n = 0 
    err = nil 
    go func() { // this goroutime still exist even when timeout
            n, err = self.reader.Read(buf) 
            ch <- true 
    }() 
    select { 
    case <-ch: 
            return 
    case <-time.After(self.timeout): 
            return 0, errors.New("Timeout") 
    } 
    return 
} 

此问题与帖子类似,但答案尚不清楚.你们有解决这个问题的好主意吗?

This question is similar in this post, but the answer is unclear.Do you guys have any good idea to solve this problem?

推荐答案

您可以关闭 os,而不是直接在 read 上设置超时.文件在超时后.如 https://golang.org/pkg/os/#File.Close

Instead of setting a timeout directly on the read, you can close the os.File after a timeout. As written in https://golang.org/pkg/os/#File.Close

这将导致您的 read 立即失败.

This should cause your read to fail immediately.

这篇关于如何在* os.File/io中设置超时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-01 17:16