Created
November 19, 2022 20:31
-
-
Save manju4ever/1bff8d80a7f50cd7cfebbfdb194b52a8 to your computer and use it in GitHub Desktop.
Context Timeout Example
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" | |
"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