pool.go 965 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. package main
  2. import (
  3. "bufio"
  4. "fmt"
  5. "os"
  6. "sync"
  7. "sync/atomic"
  8. "time"
  9. "github.com/tal-tech/go-zero/core/lang"
  10. "github.com/tal-tech/go-zero/core/syncx"
  11. )
  12. func main() {
  13. var count int32
  14. var consumed int32
  15. pool := syncx.NewPool(80, func() interface{} {
  16. fmt.Printf("+ %d\n", atomic.AddInt32(&count, 1))
  17. return 1
  18. }, func(interface{}) {
  19. fmt.Printf("- %d\n", atomic.AddInt32(&count, -1))
  20. }, syncx.WithMaxAge(time.Second))
  21. var waitGroup sync.WaitGroup
  22. quit := make(chan lang.PlaceholderType)
  23. waitGroup.Add(100)
  24. for i := 0; i < 100; i++ {
  25. go func() {
  26. defer func() {
  27. waitGroup.Done()
  28. fmt.Println("routine quit")
  29. }()
  30. for {
  31. select {
  32. case <-quit:
  33. return
  34. default:
  35. x := pool.Get().(int)
  36. atomic.AddInt32(&consumed, 1)
  37. pool.Put(x)
  38. }
  39. }
  40. }()
  41. }
  42. bufio.NewReader(os.Stdin).ReadLine()
  43. close(quit)
  44. fmt.Println("quitted")
  45. waitGroup.Wait()
  46. fmt.Printf("consumed %d\n", atomic.LoadInt32(&consumed))
  47. }