You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

bucket_pool.go 1.2 kB

11 months ago
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. package sync2
  2. import "sync"
  3. type BucketPool[T any] struct {
  4. empty []T
  5. filled []T
  6. emptyCond *sync.Cond
  7. filledCond *sync.Cond
  8. }
  9. func NewBucketPool[T any]() *BucketPool[T] {
  10. return &BucketPool[T]{
  11. emptyCond: sync.NewCond(&sync.Mutex{}),
  12. filledCond: sync.NewCond(&sync.Mutex{}),
  13. }
  14. }
  15. func (p *BucketPool[T]) GetEmpty() (T, bool) {
  16. p.emptyCond.L.Lock()
  17. defer p.emptyCond.L.Unlock()
  18. if len(p.empty) == 0 {
  19. p.emptyCond.Wait()
  20. }
  21. if len(p.empty) == 0 {
  22. var t T
  23. return t, false
  24. }
  25. t := p.empty[0]
  26. p.empty = p.empty[1:]
  27. return t, true
  28. }
  29. func (p *BucketPool[T]) PutEmpty(t T) {
  30. p.emptyCond.L.Lock()
  31. defer p.emptyCond.L.Unlock()
  32. p.empty = append(p.empty, t)
  33. p.emptyCond.Signal()
  34. }
  35. func (p *BucketPool[T]) GetFilled() (T, bool) {
  36. p.filledCond.L.Lock()
  37. defer p.filledCond.L.Unlock()
  38. if len(p.filled) == 0 {
  39. p.filledCond.Wait()
  40. }
  41. if len(p.filled) == 0 {
  42. var t T
  43. return t, false
  44. }
  45. t := p.filled[0]
  46. p.filled = p.filled[1:]
  47. return t, true
  48. }
  49. func (p *BucketPool[T]) PutFilled(t T) {
  50. p.filledCond.L.Lock()
  51. defer p.filledCond.L.Unlock()
  52. p.filled = append(p.filled, t)
  53. p.filledCond.Signal()
  54. }
  55. func (p *BucketPool[T]) WakeUpAll() {
  56. p.emptyCond.Broadcast()
  57. p.filledCond.Broadcast()
  58. }