美文网首页
Go语言学习笔记-并发编程-任务的取消

Go语言学习笔记-并发编程-任务的取消

作者: noonenote | 来源:发表于2019-04-24 18:05 被阅读0次
    package concurrency
    
    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_2(cancelChan)
        time.Sleep(time.Second * 1)
    }
    

    相关文章

      网友评论

          本文标题:Go语言学习笔记-并发编程-任务的取消

          本文链接:https://www.haomeiwen.com/subject/pwligqtx.html