美文网首页
2022-05-19

2022-05-19

作者: 新牛藕 | 来源:发表于2022-05-19 23:03 被阅读0次
    // You can edit this code!
    // Click here and start typing.
    package main
    
    import (
        "context"
        "fmt"
        "sync"
        "time"
    
        "golang.org/x/time/rate"
    )
    
    var printMux sync.Mutex
    
    func print(i int, status string) {
        printMux.Lock()
        defer printMux.Unlock()
        fmt.Printf("%s %3d %s \n", time.Now(), i, status)
    }
    
    var mux sync.Mutex
    var limiter *rate.Limiter
    
    func checkAndRun(j int, wg *sync.WaitGroup) {
        defer wg.Done()
        if !mux.TryLock() {
            print(j, "return")
            return
        }
        print(j, "locked at")
        _ = limiter.Wait(context.Background())
    
        print(j, "after wait")
        mux.Unlock()
        print(j, "end+++++++++++++++++++++++++")
    }
    func main() {
        runTimes := 50
        limiter = rate.NewLimiter(1, 1)
    
        print(-1, "start")
        var wg sync.WaitGroup
        wg.Add(runTimes)
        for i := 0; i < runTimes; i++ {
            time.Sleep(100 * time.Millisecond)
            go checkAndRun(i, &wg)
        }
        wg.Wait()
        print(-1, "END")
    }
    

    相关文章

      网友评论

          本文标题:2022-05-19

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