Andrew Gerrand | 5bc444d | 2014-12-10 11:35:11 +1100 | [diff] [blame] | 1 | # Timeouts and Deadlines |
| 2 | |
| 3 | To abandon synchronous calls that run too long, use the select statement with time.After: |
| 4 | ``` |
| 5 | import "time" |
| 6 | |
| 7 | c := make(chan error, 1) |
| 8 | go func() { c <- client.Call("Service.Method", args, &reply) } () |
| 9 | select { |
| 10 | case err := <-c: |
| 11 | // use err and reply |
| 12 | case <-time.After(timeoutNanoseconds): |
| 13 | // call timed out |
| 14 | } |
| 15 | ``` |
| 16 | |
| 17 | Note that the channel ` c ` has a buffer size of 1. If it were an unbuffered channel and the client.Call method took more than ` timeoutNanoseconds `, the channel send would block forever and the goroutine would never be destroyed. |
| 18 | |
| 19 | ## References |
| 20 | |
| 21 | time.After: http://golang.org/pkg/time/#After |
| 22 | |
| 23 | select: http://golang.org/doc/go_spec.html#Select_statements |
| 24 | |
| 25 | blog post: http://blog.golang.org/2010/09/go-concurrency-patterns-timing-out-and.html |