美文网首页
Go实现CountDownLatch

Go实现CountDownLatch

作者: 我不懂我不懂a | 来源:发表于2022-10-29 12:59 被阅读0次

    go语言用的不熟,没找到对应Java的CountDownLatch,就自己写一个......试了试好像能用

    ps:拿go造轮子真的快乐啊

    package main
    
    import (
        "fmt"
        "sync"
        "time"
    )
    
    type DownLatch struct {
        wg sync.WaitGroup
    }
    
    func instance(count int) DownLatch {
        latch := DownLatch{}
        latch.wg.Add(count)
        return latch
    }
    
    func (latch *DownLatch) Down() {
        latch.wg.Done()
    }
    
    func (latch *DownLatch) Wait() {
        latch.wg.Wait()
    }
    
    func (latch *DownLatch) WaitTime(t time.Duration) {
        waitCh := make(chan struct{})
        go func() {
            latch.wg.Wait()
            close(waitCh)
        }()
        select {
        case <-waitCh:
            return
        case <-time.After(t):
            return
        }
    }
    
    func main() {
        latch := instance(3)
        go func() {
            for i := 0; i < 3; i++ {
                time.Sleep(1 * time.Second)
                go func() {
                    latch.Down()
                    fmt.Println("count down")
                }()
            }
        }()
    
        latch.WaitTime(4 * time.Second)
        fmt.Println("keep going")
    
        time.Sleep(3 * time.Second)
        fmt.Println("end")
    }
    
    

    相关文章

      网友评论

          本文标题:Go实现CountDownLatch

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