title: How to know if the context has been cancelled?
body: <p>How to know if a context has been cancelled?</p>
  <p>In a following sample code,</p>
  <ul>
  <li>There are 2 tasks.</li>
  <li>If any of these tasks completes first, I want to know in other tasks through context cancel.</li>
  <li>As part of example, task2 will always finish first (before task1).</li>
  </ul>
  <pre class="lang-golang prettyprint-override"><code>package main
  
  import (
      &quot;context&quot;
      &quot;fmt&quot;
      &quot;time&quot;
  )
  
  func task2(ctx context.Context, ch chan int) {
      for i := 0; i &lt;= 10; i++ {
          if ctx.Err() != nil {
              // In case task1 completes first,
              // I want to print this error. How do I reach this block?
              fmt.Println(&quot;Cancelled 2&quot;, ctx.Err())
          }
  
          fmt.Println(&quot;Task2 ===== &quot;, i)
          time.Sleep(1 * time.Second)
          if i == 2 {
              ch &lt;- 2
          }
      }
  }
  
  func task1(ctx context.Context, ch chan int) {
      for i := 0; i &lt;= 10; i++ {
          if ctx.Err() != nil {
              // In case task2 completes first,
              // I want to print this error. How do I reach this block?
              fmt.Println(&quot;Cancelled 1&quot;, ctx.Err())
          }
  
          fmt.Println(&quot;Task1 ----- &quot;, i)
          time.Sleep(1 * time.Second)
          if i == 5 {
              ch &lt;- 1
          }
      }
  }
  
  func main() {
      ctx, cancel := context.WithCancel(context.Background())
      ch := make(chan int)
  
      go task1(ctx, ch)
      go task2(ctx, ch)
      
      d := &lt;-ch
      cancel() // If either of task1 or task2 completes, invoke the cancel() func
  
      fmt.Println(&quot;Task which completed first: &quot;, d)
  }
  </code></pre>