// 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")
}
网友评论