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.

allocator.h 2.2 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. /**
  2. * Copyright 2019 Huawei Technologies Co., Ltd
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. #ifndef PREDICT_SRC_RUNTIME_ALLOCATOR_H_
  17. #define PREDICT_SRC_RUNTIME_ALLOCATOR_H_
  18. #include <memory>
  19. #include <string>
  20. #include <vector>
  21. #include <mutex>
  22. #include "common/module_registry.h"
  23. namespace mindspore {
  24. namespace predict {
  25. struct AllocatorContext {
  26. int shiftFactor;
  27. bool lockFlag;
  28. };
  29. class Allocator {
  30. public:
  31. Allocator() : name("default") {}
  32. virtual ~Allocator() {}
  33. virtual void *Malloc(size_t size) = 0;
  34. virtual void Free(void *ptr) = 0;
  35. virtual void SetContext(const AllocatorContext &ctx) {}
  36. virtual size_t GetTotalSize() { return 0; }
  37. virtual void Clear() {}
  38. static std::shared_ptr<Allocator> Create();
  39. std::string name;
  40. };
  41. class DefaultAllocator : public Allocator {
  42. public:
  43. DefaultAllocator();
  44. ~DefaultAllocator() override;
  45. void SetContext(const AllocatorContext &ctx) override;
  46. void *Malloc(size_t size) override;
  47. void Free(void *ptr) override;
  48. size_t GetTotalSize() override;
  49. void Clear() override;
  50. private:
  51. void Lock();
  52. void UnLock();
  53. struct MemBuf {
  54. size_t size;
  55. void *buf;
  56. };
  57. std::mutex lock;
  58. std::vector<MemBuf *> allocatedList;
  59. std::vector<MemBuf *> freeList;
  60. int shiftFactor = 0;
  61. bool lockFlag = false;
  62. };
  63. // these declaration are for module integration, refer to sample_allocator
  64. const char MODULE_REG_NAME_ALLOCATOR[] = "allocator";
  65. template <> class Module<Allocator> : public ModuleBase {
  66. public:
  67. virtual std::shared_ptr<Allocator> Create() = 0;
  68. };
  69. } // namespace predict
  70. } // namespace mindspore
  71. #endif // PREDICT_SRC_RUNTIME_ALLOCATOR_H_