github.com/nibnait/go-learn@v0.0.0-20220227013611-dfa47ea6d2da/src/test/chapter/ch4/29_cancel_test.go (about)

     1  package ch4
     2  
     3  import (
     4  	"fmt"
     5  	"testing"
     6  	"time"
     7  )
     8  
     9  func isCancelled1(cancelChan chan struct{}) bool {
    10  	select {
    11  	case <-cancelChan:
    12  		return true
    13  	default:
    14  		return false
    15  	}
    16  }
    17  
    18  func cancel_1(cancelChan chan struct{}) {
    19  	cancelChan <- struct{}{}
    20  }
    21  
    22  func cancel_2(cancelChan chan struct{}) {
    23  	close(cancelChan)
    24  }
    25  
    26  func TestCancel1(t *testing.T) {
    27  	cancelChan := make(chan struct{}, 0)
    28  
    29  	for i := 0; i < 5; i++ {
    30  		go func(i int, cancelCh chan struct{}) {
    31  			for {
    32  				if isCancelled1(cancelCh) {
    33  					break
    34  				}
    35  				time.Sleep(time.Millisecond * 5)
    36  			}
    37  			fmt.Println(i, "Cancelled")
    38  		}(i, cancelChan)
    39  	}
    40  
    41  	cancel_1(cancelChan)
    42  	//cancel_2(cancelChan)
    43  	time.Sleep(time.Second * 1)
    44  }