1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94
| package main
import ( "context" "fmt" "sync" "time" )
func main() { var wg sync.WaitGroup ctx, cancel := context.WithCancel(context.Background()) defer cancel()
wg.Add(1) go func() { defer wg.Done() if err := printGreet(ctx); err != nil { fmt.Printf("cannot print greeting: %v\n", err) cancel() } }()
wg.Add(1) go func() { defer wg.Done() if err := printFarewell(ctx); err != nil { fmt.Printf("cannot print farewell: %v\n", err) } }()
wg.Wait() }
func printGreet(ctx context.Context) error { greeting, err := genGreeting(ctx) if err != nil { return err } fmt.Printf("%s world!\n", greeting) return nil }
func printFarewell(ctx context.Context) error { farewell, err := genFarewell(ctx) if err != nil { return err } fmt.Printf("%s world!\n", farewell) return nil }
func genGreeting(ctx context.Context) (string, error) { ctx, cancel := context.WithTimeout(ctx, 1*time.Second) defer cancel()
switch locale, err := locale(ctx); { case err != nil: return "", err case locale == "ZH/CN": return "你好", nil } return "", fmt.Errorf("unsupported locale") }
func genFarewell(ctx context.Context) (string, error) { switch locale, err := locale(ctx); { case err != nil: return "", err case locale == "ZH/CN": return "再见", nil } return "", fmt.Errorf("unsupported locale") }
func locale(ctx context.Context) (string, error) { if deadline, ok := ctx.Deadline(); ok { if deadline.Sub(time.Now().Add(1*time.Minute)) <= 0 { return "", context.DeadlineExceeded } }
select { case <-ctx.Done(): return "", ctx.Err() case <-time.After(1 * time.Minute): } return "ZH/CN", nil }
|