Created
March 13, 2019 10:05
-
-
Save mmierzwa/c9adb36aabfde83e492d61550ca7ccef to your computer and use it in GitHub Desktop.
timeout and synchronization
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" | |
"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