Created
February 26, 2023 12:05
-
-
Save psankar/882e5aaf3f0f4bf0480d21d1d8ea5977 to your computer and use it in GitHub Desktop.
golang cancel context example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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