coop.Timeout doesn't cancel running fn on timeout
It should be noted that coop.Timeout has a TODO: https://github.com/rakyll/coop/blob/master/coop.go#L70
I'm wondering how you would be able to cancel a running goroutine.... I really can't think of anything without having the goroutine 'knowing' how to stop (select receiving a channel periodically and acting when it's closed)
I don't think it's very good that a 918 star project makes an impossible promise in README.md. Please change the documentation for coop.Timeout (or remove it all together since everyone using it is expecting behavior thats not actually happening.)
The only case where behaviour will be as expected is when main() ends before the fn is finished.
func main() {
done := coop.Timeout(time.Second, func() {
time.Sleep(2 * time.Second)
fmt.Println("Hello world")
})
<-done // will return false, because timeout occurred
}
When adding a sleep after the receive on the channel done, it still lets the fn finish (it isn't canceled)
func main() {
done := coop.Timeout(time.Second, func() {
time.Sleep(2 * time.Second)
fmt.Println("Hello world")
})
<-done // will return false, because timeout occurred
time.Sleep(3 * time.Second)
}
And after that coop panics:
Hello world
panic: send on closed channel
goroutine 6 [running]:
github.com/rakyll/coop.func·005()
/home/geertjohan/src/github.com/rakyll/coop/coop.go:79 +0x66
created by github.com/rakyll/coop.Timeout
/home/geertjohan/src/github.com/rakyll/coop/coop.go:80 +0x1b8
goroutine 1 [sleep]:
time.Sleep(0xb2d05e00)
/home/geertjohan/go/src/runtime/time.go:59 +0x105
main.main()
/home/geertjohan/blah.go:16 +0x64
exit status 2
I am curious that "ToDo" is possible?
I need to know if once timeout can I kill that goroutine? or simply put <-done because I don't need it anymore?
It won't kill the goroutine. The Timeout function doesn't actually implement what it promises. It's imposible to do it like that. You're better off writing your own concurrency patterns.
The Go runtime doesn't provide mechanisms to stop an executing goroutine. You may structure your goroutine to react to a signal and return to exit. Such a scenario will require you to develop a mechanism momentarily stop executing your actual task and try to read the signal (most likely from a channel).
Thanks for reminding me that I should have removed the Timeout function.
In my use case this isn't a serious limitation. I can listen to the signal. I am not sure how other developers will react to this. Thanks to both for your comments.