context 介紹

package main

import(
   "context"
   "fmt"
   "time"
)

func main() {
   ctx, cancel := context.WithCancel(context.Background())
   
   go func() {
      for {
         select {
            case <-ctx.Done():
               fmt.Println("Job done.")
               return
            default:
               fmt.Println("Still working")
               time.Sleep(1 * time.Second)
         }
      }
   }()

   time.Sleep(5 * time.Second)
   fmt.Println("Stop job")
   cancel()
   time.Sleep(5 * time.Second)
}

package main

import(
   "context"
   "fmt"
   "time"
)

func worker(ctx context.Context,  name string) {
   go func() {
      for {
         select {
            case <-ctx.Done():
               fmt.Println("job done")
               return
            default:
               fmt.Println(name, " Still working")
               time.Sleep(1 * time.Second)
         }
      }
   }()
} 

func main() {
   ctx, cancel := context.WithCancel(context.Background())

   go worker(ctx, "job A")
   go worker(ctx, "job B")
   go worker(ctx, "job C")
   go worker(ctx, "job D")

   time.Sleep(5 * time.Second)
   fmt.Println("Stop the ctx")
   cancel()
   time.Sleep(3 * time.Second)
}