title: Cancellation pattern in Golang
body: <p>Here is a quote from <a href="http://devs.cloudimmunity.com/gotchas-and-common-mistakes-in-go-golang/index.html#blocked_goroutines" rel="nofollow noreferrer">50 Shades Of Go: Traps, Gotchas and Common mistakes</a>:</p>
  
  <blockquote>
    <p>You can also use a special cancellation channel to interrupt the
    workers.</p>
  </blockquote>
  
  <pre><code>func First(query string, replicas ...Search) Result {  
      c := make(chan Result)
      done := make(chan struct{})
      defer close(done)
      searchReplica := func(i int) { 
          select {
          case c &lt;- replicas[i](query):
          case &lt;- done:
          }
      }
      for i := range replicas {
          go searchReplica(i)
      }
  
      return &lt;-c
  }
  </code></pre>
  
  <p>As far as understand, it means that we use channel <code>done</code> to interrupt the workers ahead of time without waiting for full execution (in our case execution of <code>replicas[i](query)</code>. Therefore, we can receive a result from the fastest worker ("First Wins Pattern") and then cancel the work in all other workers and save the resources.</p>
  
  <p>On the other hand, according to the <a href="https://golang.org/ref/spec#Select_statements" rel="nofollow noreferrer">specification</a>: </p>
  
  <blockquote>
    <p>For all the cases in the statement, the channel operands of receive
    operations and the channel and right-hand-side expressions of send
    statements are evaluated exactly once, in source order, upon entering
    the "select" statement.</p>
  </blockquote>
  
  <p>As far as I understand, it means we cannot <code>interrupt the workers</code>, as in any case, all workers will evaluate function <code>replicas[i]query</code> and only then select <code>case &lt;- done</code> and finish their execution.</p>
  
  <p>Could you please point out at the mistake in my reasoning?</p>