tokens.go 616 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. package snowflake_proxy
  2. import (
  3. "sync/atomic"
  4. )
  5. type tokens_t struct {
  6. ch chan struct{}
  7. capacity uint
  8. clients int64
  9. }
  10. func newTokens(capacity uint) *tokens_t {
  11. var ch chan struct{}
  12. if capacity != 0 {
  13. ch = make(chan struct{}, capacity)
  14. }
  15. return &tokens_t{
  16. ch: ch,
  17. capacity: capacity,
  18. clients: 0,
  19. }
  20. }
  21. func (t *tokens_t) get() {
  22. atomic.AddInt64(&t.clients, 1)
  23. if t.capacity != 0 {
  24. t.ch <- struct{}{}
  25. }
  26. }
  27. func (t *tokens_t) ret() {
  28. atomic.AddInt64(&t.clients, -1)
  29. if t.capacity != 0 {
  30. <-t.ch
  31. }
  32. }
  33. func (t tokens_t) count() int64 {
  34. return atomic.LoadInt64(&t.clients)
  35. }