Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
package main
import (
"context"
"time"
"fmt"
"sync"
)
// try context.Deadline
func main() {
var wg sync.WaitGroup
ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(2 * time.Second))
defer cancel()
ch := make(chan string)
wg.Add(1)
go func() {
defer wg.Done()
defer close(ch)
var hello string
fmt.Println("now waiting to recive cancel...")
hello = "Hello"
LOOP:
for {
fmt.Println("in for")
select {
case ch <- hello:
fmt.Println("ok get hello")
case <-ctx.Done():
fmt.Println("Received cancel")
fmt.Printf("done func. cancle reason: %v\n", ctx.Err())
break LOOP
}
}
fmt.Println("end func")
}()
fmt.Printf("%s, World!\n", <-ch)
wg.Wait()
fmt.Println("Completed.")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment