【Duke】任务的取消 026 - PingPongGooo/GoFoundation GitHub Wiki

任务的取消

package cancel_by_close

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

func isCancelled(cancelChan chan struct{}) bool {
	select {
	case <- cancelChan:
		return true
	default:
		return false
	}
}

func cancel_1(cancelChan chan  struct{})  {
	cancelChan <- struct{}{}
}

func cancel_2(cancelChan chan struct{}){
	close(cancelChan)
}

func TestCancel(t *testing.T)  {
	cancelChan := make(chan struct{}, 0)
	for i := 0; i < 5; i++ {
		go func(i int, cancelCh chan struct{}) {
			for {
				if isCancelled(cancelCh){
					break
				}
				time.Sleep(time.Millisecond * 5)
			}
			fmt.Println(i, "Cancelled")
		}(i, cancelChan)
	}

	cancel_1(cancelChan)
	//=== RUN   TestCancel
	//4 Cancelled
	//--- PASS: TestCancel (1.00s)
	//PASS

	//cancel_2(cancelChan) // 广播机制。
	//=== RUN   TestCancel
	//2 Cancelled
	//1 Cancelled
	//4 Cancelled
	//3 Cancelled
	//0 Cancelled
	//--- PASS: TestCancel (1.00s)

	time.Sleep(time.Second * 1)
}