context与任务取消

2021-04-09  本文已影响0人  MrBryan
package channel_close

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

func isCancelled(ctx context.Context) bool {
    select {
    case <-ctx.Done():
        return true

    default:
        return false
    }
}

func TestCancel(t *testing.T) {
    ctx, cancel := context.WithCancel(context.Background())

    for i := 0; i < 5; i++ {
        go func(i int, ctx context.Context) {
            for {
                if isCancelled(ctx) {
                    break
                }
                time.Sleep(time.Millisecond * 5)
            }
            fmt.Println(i, "Cancelled")
        }(i, ctx)
    }
    cancel()

    time.Sleep(time.Second * 1)

}

上一篇 下一篇

猜你喜欢

热点阅读