{"id":2189,"date":"2017-04-28T20:14:45","date_gmt":"2017-04-29T01:14:45","guid":{"rendered":"http:\/\/www.wiredprairie.us\/blog\/?p=2189"},"modified":"2017-04-28T20:14:45","modified_gmt":"2017-04-29T01:14:45","slug":"quick-demo-of-gos-context-withtimeout","status":"publish","type":"post","link":"https:\/\/www.wiredprairie.us\/blog\/index.php\/archives\/2189","title":{"rendered":"Quick demo of Go’s context.WithTimeout"},"content":{"rendered":"

To better understand Go’s context withTimeout\u00a0<\/strong><\/a>functionality (and as a reference for myself), I’ve created this small self-contained demo. I didn’t find the published documentation’s example to be clear enough. The interesting part, coming from other programming languages and platforms, was that the WithTimeout<\/strong> function only was a signal that something happened. It doesn’t do anything when there’s a time out (like abort a goroutine or anything dramatic like that).<\/p>\n

The essential pieces:<\/p>\n

    \n
  1. Call WithTimeout<\/strong> passing the Background()<\/strong> context and specify the timeout (I’ve specified \u00a03.2 seconds)<\/li>\n
  2. Be a good citizen and defer<\/strong> the cancellation (to be sure that it’s called) and\u00a0defer close\u00a0<\/strong>the channel<\/li>\n
  3. Start the go routine which waits for the Done\u00a0<\/strong>channel<\/li>\n
  4. When the Done<\/strong> is signaled, display the current time in seconds and what caused the signal<\/li>\n
  5. The main app is waiting for the goroutine to end, so signal that.<\/li>\n
  6. In the main function, the code sleeps and wakes emitting some time stamps to the console<\/li>\n
  7. Depending on whether cancel<\/strong> is called, the goroutine signal may be one of two things.\n
      \n
    1. If cancel<\/strong> is not called prior to the second sleep in\u00a0the code, the ctx.Err()\u00a0<\/strong>returns\n
      <-ctx.Done():  context deadline exceeded<\/span><\/pre>\n<\/li>\n
    2. If cancel<\/strong> however is called, the ctx.Err() returns:\n
      <-ctx.Done():  context canceled<\/span><\/pre>\n<\/li>\n<\/ol>\n<\/li>\n
    3. Then, the goroutine uses the channel to signal completion (wait<-true<\/strong>).<\/li>\n<\/ol>\n