cond_wait.go 509 B

1234567891011121314151617181920212223242526272829303132
  1. package util
  2. import (
  3. "context"
  4. "net/http"
  5. "sync"
  6. "time"
  7. )
  8. const HttpStatusCancelled = 499
  9. func WaitWithTimeout(ctx context.Context, cond *sync.Cond, timer *time.Timer) int {
  10. waitDone := make(chan struct{})
  11. go func() {
  12. cond.L.Lock()
  13. defer cond.L.Unlock()
  14. cond.Wait()
  15. defer close(waitDone)
  16. }()
  17. select {
  18. case <-waitDone:
  19. return http.StatusOK
  20. case <-timer.C:
  21. cond.Broadcast()
  22. return http.StatusTooManyRequests
  23. case <-ctx.Done():
  24. cond.Broadcast()
  25. return HttpStatusCancelled
  26. }
  27. }