conditional_allocator.h 1.7 KB
Newer Older
Y
Yu Yang 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
// Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#pragma once
#include <functional>
17
#include <memory>
Y
Yu Yang 已提交
18 19 20 21 22 23 24 25
#include <utility>
#include <vector>
#include "paddle/fluid/memory/allocation/allocator.h"

namespace paddle {
namespace memory {
namespace allocation {

Y
Yu Yang 已提交
26 27 28 29 30 31
// A composite allocator who will dispatch the allocation request by registered
// condition.
//
// For example:
//
// auto* cond_allocator = new ConditionalAllocator();
32
// cond_allocator->AddAllocator([](size_t size){
Y
Yu Yang 已提交
33 34
//   // if size > 10
//   return size > 10;
35
// }, allocator_b).AddAllocator([](size_t size){
Y
Yu Yang 已提交
36 37 38
//   // else
//   return true;
// }, allocator_c);
Y
Yu Yang 已提交
39
class ConditionalAllocator : public Allocator {
Y
Yu Yang 已提交
40 41 42
 public:
  ConditionalAllocator() = default;

43
  ConditionalAllocator& AddAllocator(std::function<bool(size_t)> func,
Y
Yu Yang 已提交
44 45
                                     std::shared_ptr<Allocator> allocator);

Y
Yu Yang 已提交
46 47
  bool IsAllocThreadSafe() const override;

Y
Yu Yang 已提交
48
 protected:
49
  Allocation* AllocateImpl(size_t size) override;
Y
Yu Yang 已提交
50

Y
Yu Yang 已提交
51
 private:
Y
Yu Yang 已提交
52
  using AllocatorWithCond =
53
      std::pair<std::function<bool(size_t)>, std::shared_ptr<Allocator>>;
Y
Yu Yang 已提交
54
  std::vector<AllocatorWithCond> underlying_allocators_;
Y
Yu Yang 已提交
55 56 57 58 59
};

}  // namespace allocation
}  // namespace memory
}  // namespace paddle