pool.go 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. package gopool
  2. import (
  3. "runtime"
  4. "time"
  5. "github.com/panjf2000/ants/v2"
  6. )
  7. var (
  8. // Init a instance pool when importing ants.
  9. defaultPool, _ = ants.NewPool(ants.DefaultAntsPoolSize, ants.WithExpiryDuration(10*time.Second))
  10. minNumberPerTask = 5
  11. )
  12. // Logger is used for logging formatted messages.
  13. type Logger interface {
  14. // Printf must have the same semantics as log.Printf.
  15. Printf(format string, args ...interface{})
  16. }
  17. // Submit submits a task to pool.
  18. func Submit(task func()) error {
  19. return defaultPool.Submit(task)
  20. }
  21. // Running returns the number of the currently running goroutines.
  22. func Running() int {
  23. return defaultPool.Running()
  24. }
  25. // Cap returns the capacity of this default pool.
  26. func Cap() int {
  27. return defaultPool.Cap()
  28. }
  29. // Free returns the available goroutines to work.
  30. func Free() int {
  31. return defaultPool.Free()
  32. }
  33. // Release Closes the default pool.
  34. func Release() {
  35. defaultPool.Release()
  36. }
  37. // Reboot reboots the default pool.
  38. func Reboot() {
  39. defaultPool.Reboot()
  40. }
  41. func Threads(tasks int) int {
  42. threads := tasks / minNumberPerTask
  43. if threads > runtime.NumCPU() {
  44. threads = runtime.NumCPU()
  45. } else if threads == 0 {
  46. threads = 1
  47. }
  48. return threads
  49. }