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

63 lines
1.1 KiB

  1. package mem
  2. import (
  3. "github.com/chrislusf/seaweedfs/weed/glog"
  4. "sync"
  5. "sync/atomic"
  6. )
  7. var pools []*sync.Pool
  8. const (
  9. min_size = 1024
  10. )
  11. func bitCount(size int) (count int) {
  12. for ; size > min_size; count++ {
  13. size = (size + 1) >> 1
  14. }
  15. return
  16. }
  17. func init() {
  18. // 1KB ~ 256MB
  19. pools = make([]*sync.Pool, bitCount(1024*1024*256))
  20. for i := 0; i < len(pools); i++ {
  21. slotSize := 1024 << i
  22. pools[i] = &sync.Pool{
  23. New: func() interface{} {
  24. buffer := make([]byte, slotSize)
  25. return &buffer
  26. },
  27. }
  28. }
  29. }
  30. func getSlotPool(size int) (*sync.Pool, bool) {
  31. index := bitCount(size)
  32. if index >= len(pools) {
  33. return nil, false
  34. }
  35. return pools[index], true
  36. }
  37. var total int64
  38. func Allocate(size int) []byte {
  39. if pool, found := getSlotPool(size); found {
  40. newVal := atomic.AddInt64(&total, 1)
  41. glog.V(4).Infof("++> %d", newVal)
  42. slab := *pool.Get().(*[]byte)
  43. return slab[:size]
  44. }
  45. return make([]byte, size)
  46. }
  47. func Free(buf []byte) {
  48. if pool, found := getSlotPool(cap(buf)); found {
  49. newVal := atomic.AddInt64(&total, -1)
  50. glog.V(4).Infof("--> %d", newVal)
  51. pool.Put(&buf)
  52. }
  53. }