Skip to content

Instantly share code, notes, and snippets.

@mmierzwa
Created March 13, 2019 10:05
Show Gist options
  • Save mmierzwa/c9adb36aabfde83e492d61550ca7ccef to your computer and use it in GitHub Desktop.
Save mmierzwa/c9adb36aabfde83e492d61550ca7ccef to your computer and use it in GitHub Desktop.
timeout and synchronization
package main
import (
"context"
"fmt"
"math/rand"
"time"
)
const timeout = time.Second
const routinesToStart = 10
var rng = rand.New(rand.NewSource(time.Now().Unix()))
func processDoubleAsync(ctx context.Context, id int) {
go func(ctx context.Context) {
ctx, cancel := context.WithTimeout(ctx, timeout)
defer cancel()
done := make(chan bool)
go func() {
process(ctx, id)
done <- true
}()
select {
case <-ctx.Done():
fmt.Printf("error: processing timeout - %d\n", id)
break
case <-done:
fmt.Printf("finished processing\n")
return
}
}(ctx)
}
func processAsync(ctx context.Context, id int) {
ctx, cancel := context.WithTimeout(ctx, timeout)
defer cancel()
done := make(chan bool)
go func() {
process(ctx, id)
done <- true
}()
select {
case <-ctx.Done():
fmt.Printf("error: processing timeout - %d\n", id)
break
case <-done:
fmt.Printf("finished processing\n")
return
}
}
func process(ctx context.Context, id int) {
fmt.Printf("processing %d started...\n", id)
sleepTime := time.Duration(rng.Int31n(2000)) * time.Millisecond
time.Sleep(sleepTime)
fmt.Printf("%d ended after %s\n", id, sleepTime)
}
func main() {
ctx := context.Background()
for i := 0; i < routinesToStart; i++ {
processDoubleAsync(ctx, i)
}
time.Sleep(time.Second * 30)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment