memory_pool.cpp 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. #include "memory_pool.h"
  2. #include <yql/essentials/public/udf/udf_allocator.h>
  3. #include <util/generic/singleton.h>
  4. #include <util/generic/yexception.h>
  5. namespace NYql {
  6. namespace NUdf {
  7. class TYqlMemoryPool : public arrow::MemoryPool {
  8. arrow::Status Allocate(int64_t size, uint8_t** out) final {
  9. Y_ENSURE(size >= 0 && out);
  10. *out = (uint8_t*)UdfArrowAllocate(size);
  11. UpdateAllocatedBytes(size);
  12. return arrow::Status::OK();
  13. }
  14. arrow::Status Reallocate(int64_t old_size, int64_t new_size, uint8_t** ptr) final {
  15. Y_ENSURE(old_size >= 0 && new_size >= 0 && ptr);
  16. *ptr = (uint8_t*)UdfArrowReallocate(*ptr, old_size, new_size);
  17. UpdateAllocatedBytes(new_size - old_size);
  18. return arrow::Status::OK();
  19. }
  20. void Free(uint8_t* buffer, int64_t size) final {
  21. Y_ENSURE(size >= 0);
  22. UdfArrowFree(buffer, size);
  23. UpdateAllocatedBytes(-size);
  24. }
  25. int64_t max_memory() const final {
  26. return max_memory_.load();
  27. }
  28. int64_t bytes_allocated() const final {
  29. return bytes_allocated_.load();
  30. }
  31. inline void UpdateAllocatedBytes(int64_t diff) {
  32. // inspired by arrow/memory_pool.h impl.
  33. int64_t allocated = bytes_allocated_.fetch_add(diff) + diff;
  34. if (diff > 0 && allocated > max_memory_) {
  35. max_memory_ = allocated;
  36. }
  37. }
  38. virtual std::string backend_name() const final {
  39. return "yql";
  40. }
  41. private:
  42. std::atomic<int64_t> bytes_allocated_{0};
  43. std::atomic<int64_t> max_memory_{0};
  44. };
  45. arrow::MemoryPool* GetYqlMemoryPool() {
  46. return Singleton<TYqlMemoryPool>();
  47. }
  48. }
  49. }