retry_allocator.cc 2.2 KB
Newer Older
S
sneaxiy 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
// 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.

#include "paddle/fluid/memory/allocation/retry_allocator.h"
Y
Yu Yang 已提交
16
#include "paddle/fluid/memory/allocation/allocation_with_underlying.h"
S
sneaxiy 已提交
17 18 19 20
namespace paddle {
namespace memory {
namespace allocation {

S
sneaxiy 已提交
21
void RetryAllocator::FreeImpl(Allocation* allocation) {
Y
Yu Yang 已提交
22
  // Delete underlying allocation first.
S
sneaxiy 已提交
23 24
  underlying_allocator_->Free(allocation);
  cv_.notify_all();
Y
Yu Yang 已提交
25 26
}

Y
Yu Yang 已提交
27
Allocation* RetryAllocator::AllocateImpl(size_t size, Allocator::Attr attr) {
S
sneaxiy 已提交
28
  auto alloc_func = [&, this]() {
S
sneaxiy 已提交
29
    return underlying_allocator_->Allocate(size, attr).release();
S
sneaxiy 已提交
30 31 32 33
  };
  // In fact, we can unify the code of allocation success and failure
  // But it would add lock even when allocation success at the first time
  try {
Y
Yu Yang 已提交
34 35
    return alloc_func();
  } catch (BadAlloc& bad_alloc) {
S
sneaxiy 已提交
36 37 38 39 40 41
    {
      // We can just write allocation retry inside the predicate function of
      // wait_until
      // But it needs to acquire the lock when executing predicate function
      // For better performance, we use loop here
      auto end_time = std::chrono::high_resolution_clock::now() + retry_time_;
Y
Yu Yang 已提交
42 43 44 45 46
      auto wait_until = [&, this] {
        std::unique_lock<std::mutex> lock(mutex_);
        return cv_.wait_until(lock, end_time);
      };
      while (wait_until() != std::cv_status::timeout) {
S
sneaxiy 已提交
47
        try {
Y
Yu Yang 已提交
48 49 50
          return alloc_func();
        } catch (BadAlloc& ex) {
          bad_alloc = ex;
S
sneaxiy 已提交
51
        } catch (...) {
Y
Yu Yang 已提交
52
          throw;
S
sneaxiy 已提交
53
        }
Y
Yu Yang 已提交
54
      }
S
sneaxiy 已提交
55

Y
Yu Yang 已提交
56
      throw;  // rethrow the original exception or throw the internal bad_alloc
S
sneaxiy 已提交
57 58
    }
  } catch (...) {
Y
Yu Yang 已提交
59 60 61
    throw;
  }
}
S
sneaxiy 已提交
62 63 64 65

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