Skip to content

Instantly share code, notes, and snippets.

@manju4ever
Created November 19, 2022 20:31
Show Gist options
  • Save manju4ever/1bff8d80a7f50cd7cfebbfdb194b52a8 to your computer and use it in GitHub Desktop.
Save manju4ever/1bff8d80a7f50cd7cfebbfdb194b52a8 to your computer and use it in GitHub Desktop.
Context Timeout Example
package main
import (
"context"
"fmt"
"time"
)
func WorkHardOne(ctx context.Context, name string, res *chan string) {
for sec := 0; sec < 3; sec++ {
fmt.Println("[WorkHardOne] Still Doing...", sec+1)
time.Sleep(time.Second * 1)
}
*res <- "/\\ Namaste " + name
}
func main() {
ctx, cancel := context.WithTimeout(context.Background(), time.Second*4)
defer cancel()
resChan := make(chan string, 1)
go WorkHardOne(ctx, "Manju", &resChan)
select {
case msg, ok := <-resChan:
{
if !ok {
fmt.Println("[main] Chan closed !")
} else {
fmt.Println("[main] Result from routine:", msg)
}
}
case <-ctx.Done():
fmt.Println("[main] Err:", ctx.Err())
}
fmt.Println("[main] Wish i did not wait for anybody !")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment