Dear all,
Let's strait to the question:
Suppose I want to read something on a Reader and make the Read call
return after a certain time period. I know the net.Conn has
SetDeadline(), but I want to apply it to generic Reader, i.e. io.Reader.
There are already some people proposed their approach long time ago and
it should not be hard. Here is my code:
http://play.golang.org/p/itXsEEseRM
Main part:
func (self *TimeoutReader) Read(buf []byte) (n int, err error) {
ch := make(chan bool)
n = 0
err = nil
go func() {
n, err = self.reader.Read(buf)
ch <- true
}()
select {
case <-ch:
return
case <-time.After(self.timeout):
return 0, errors.New("Timeout")
}
return
}
I won't explain too much on it. It's easy and you get the idea.
However, this code will cause the goroutine created in Read() always run
if the Read() did not return.
Is there any other way to make the goroutine stop running? (I think it
turns to be another old problem on this list: How to kill a goroutine
externally. Well.. I know the answer is: No, we cannot do it.)
Anyway, here is a possible solution I can image:
Test if the reader has a method named SetReadDeadline() or SetDeadline()
by defining new interfaces. If it does, use it to set timeout.
Does anyone has other (better) solutions?
Regards,
-Monnand
--