Skip to content

Instantly share code, notes, and snippets.

@psankar
Created February 26, 2023 12:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save psankar/882e5aaf3f0f4bf0480d21d1d8ea5977 to your computer and use it in GitHub Desktop.
Save psankar/882e5aaf3f0f4bf0480d21d1d8ea5977 to your computer and use it in GitHub Desktop.
golang cancel context example
package main
import (
"context"
"fmt"
"math/rand"
"sync"
"time"
)
var wg sync.WaitGroup
func fn(ctx context.Context, threadName string, cancel context.CancelFunc) {
defer cancel()
defer wg.Done()
select {
case <-time.After(time.Duration(rand.Intn(500)) * time.Millisecond):
fmt.Println(threadName, "done")
case <-ctx.Done():
fmt.Println(threadName, "cancelled")
}
}
func main() {
// Create a new context
ctx := context.Background()
// Create a new context, with its cancellation function
// from the original context
ctx, cancel := context.WithCancel(ctx)
num_threads := 10
wg.Add(num_threads)
for i := 0; i < num_threads; i++ {
go fn(ctx, fmt.Sprintf("thread%d", i), cancel)
}
wg.Wait()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment