Go实现CountDownLatch

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)