This commit is contained in:
2023-03-01 11:23:26 +08:00
commit e6ee860fd9
46 changed files with 1628 additions and 0 deletions
@@ -0,0 +1,35 @@
package cancel_by_context_test
import (
"context"
"fmt"
"testing"
"time"
)
func isCancelled(ctx context.Context) bool {
select {
case <-ctx.Done():
return true
default:
return false
}
}
// 使用context来取消任务
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, "Done")
}(i, ctx)
}
cancel()
time.Sleep(time.Second * 1)
}