Skip to content

Instantly share code, notes, and snippets.

@Neio
Last active April 18, 2018 03:00
Show Gist options
  • Save Neio/a7e56c633e66c81df1c41fbbee57d0d7 to your computer and use it in GitHub Desktop.
Save Neio/a7e56c633e66c81df1c41fbbee57d0d7 to your computer and use it in GitHub Desktop.
[GO] Run with cancellation
package main
import (
"context"
"fmt"
"time"
)
func main() {
ctx, cancel := context.WithCancel(context.Background())
go func() {
select {
case <-ctx.Done():
fmt.Printf("%v Cancelled \n", time.Now().String())
case <-time.After(1 * time.Microsecond):
fmt.Printf("%v Run \n", time.Now().String())
}
}()
fmt.Printf("%v Start\n", time.Now().String())
time.Sleep(2 * time.Microsecond)
fmt.Printf("%v Finish\n", time.Now().String())
cancel()
time.Sleep(1 * time.Microsecond)
fmt.Printf("%v Exit\n", time.Now().String())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment