title: Context cancelled by timeout but computation is not aborted?
body: <p>Trying to understand how go context cancellation will abort execution of subsequent code</p>
  <p>Details of experiment:</p>
  <ol>
  <li>main func has a context that times out in <code>2sec</code></li>
  <li>main func calls another func <code>sum</code> in a separate go-routine - which sleeps for <code>1sec</code> for test-run-1  &amp; <code>4sec</code> for test-run-2</li>
  <li>letting main sleep for <code>3sec</code> to let spun go-routine complete execution</li>
  </ol>
  <pre><code>package main
  
  import (
      &quot;context&quot;
      &quot;fmt&quot;
      &quot;log&quot;
      &quot;time&quot;
  )
  
  func main() {
  
      c := context.Background()
      childCtx, cancel := context.WithTimeout(c, 2*time.Second)
      defer cancel()
  
      ch := make(chan int, 1)
      go sum(5, 6, ch)
  
      var msg string
  
      select {
      case &lt;-childCtx.Done():
          msg = &quot;return from ctx done channel&quot;
      case res := &lt;-ch:
          msg = fmt.Sprintf(&quot;return from go routine: %v&quot;, res)
      }
  
      log.Print(msg)
  
      time.Sleep(3 * time.Second) //sleeping here to test if go-routine is still running
  }
  
  
  func sum(x int, y int, c chan&lt;- int) {
      time.Sleep(1 * time.Second) 
      //testcase-1: sleep - 1s
      //testcase-2: sleep - 4s
  
      result := x + y
  
      log.Printf(&quot;print from sum fn: %v&quot;, result)
  
      c &lt;- result
  }
  </code></pre>
  <p>Response for testcase-1 : sleep sum function for 1 sec:</p>
  <pre><code>2021/04/12 01:06:58 print from sum fn: 11
  2021/04/12 01:06:58 return from go routine: 11
  </code></pre>
  <p>Response for testcase-2 : sleep sum function for 4 sec:</p>
  <pre><code>2021/04/12 01:08:25 return from ctx done channel
  2021/04/12 01:08:27 print from sum fn: 11
  </code></pre>
  <p>In testcase-2 when sum func sleeps for 4 secs, context is already cancelled by timeout after 2secs, why is it still executing the sum func in diff go-routine and printing <code>print from sum fn: 1</code> ?</p>
  <p>From documentation: <a href="https://golang.org/pkg/context/#example_WithTimeout" rel="nofollow noreferrer">Canceling this context releases resources associated with it.</a></p>
  <p>My assumption is that all the computation will be aborted immediately after 2 secs including the spun go-routine</p>
  <p>Let me know how to do this right, thanks in adavance</p>