Created
November 25, 2022 20:32
-
-
Save debedb/4b9a22033b9de5ed5ae68dabe7d86b2b to your computer and use it in GitHub Desktop.
Go: Contexts
This file contains hidden or 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" | |
"sync" | |
"time" | |
) | |
func withCancel() { | |
var wg sync.WaitGroup | |
ctx, cancel := context.WithCancel(context.Background()) | |
go func() { | |
ch := ctx.Done() | |
defer wg.Done() | |
fmt.Println("Done: ", <-ch) | |
}() | |
go func() { | |
defer wg.Done() | |
d, _ := time.ParseDuration("100ms") | |
fmt.Printf("Will manually cancel in %s\n", d) | |
time.Sleep(d) | |
cancel() | |
}() | |
wg.Add(2) | |
wg.Wait() | |
} | |
func withTimeout() { | |
var wg sync.WaitGroup | |
d, _ := time.ParseDuration("100ms") | |
fmt.Printf("Will auto-cancel in %s\n", d) | |
ctx, _ := context.WithTimeout(context.Background(), d) | |
go func() { | |
ch := ctx.Done() | |
defer wg.Done() | |
fmt.Println("Done: ", <-ch) | |
}() | |
wg.Add(1) | |
wg.Wait() | |
} | |
func main() { | |
withCancel() | |
withTimeout() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment