retry_allocator.cc 2.1 KB
Newer Older
S
sneaxiy 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
// 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"
namespace paddle {
namespace memory {
namespace allocation {

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

26
Allocation* RetryAllocator::AllocateImpl(size_t size) {
S
sneaxiy 已提交
27
  auto alloc_func = [&, this]() {
28
    return underlying_allocator_->Allocate(size).release();
S
sneaxiy 已提交
29 30 31 32
  };
  // 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 已提交
33 34
    return alloc_func();
  } catch (BadAlloc& bad_alloc) {
S
sneaxiy 已提交
35 36 37 38 39 40
    {
      // 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 已提交
41 42 43 44 45
      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 已提交
46
        try {
Y
Yu Yang 已提交
47 48 49
          return alloc_func();
        } catch (BadAlloc& ex) {
          bad_alloc = ex;
S
sneaxiy 已提交
50
        } catch (...) {
Y
Yu Yang 已提交
51
          throw;
S
sneaxiy 已提交
52
        }
Y
Yu Yang 已提交
53
      }
S
sneaxiy 已提交
54

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

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