• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /* Copyright 2015 The TensorFlow Authors. All Rights Reserved.
2 
3 Licensed under the Apache License, Version 2.0 (the "License");
4 you may not use this file except in compliance with the License.
5 You may obtain a copy of the License at
6 
7     http://www.apache.org/licenses/LICENSE-2.0
8 
9 Unless required by applicable law or agreed to in writing, software
10 distributed under the License is distributed on an "AS IS" BASIS,
11 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 See the License for the specific language governing permissions and
13 limitations under the License.
14 ==============================================================================*/
15 
16 #include "tensorflow/core/common_runtime/allocator_retry.h"
17 #include "tensorflow/core/platform/env.h"
18 #include "tensorflow/core/platform/logging.h"
19 #include "tensorflow/core/platform/mutex.h"
20 #include "tensorflow/core/platform/types.h"
21 
22 namespace tensorflow {
23 
AllocatorRetry()24 AllocatorRetry::AllocatorRetry() : env_(Env::Default()) {}
25 
AllocateRaw(std::function<void * (size_t alignment,size_t num_bytes,bool verbose_failure)> alloc_func,int max_millis_to_wait,size_t alignment,size_t num_bytes)26 void* AllocatorRetry::AllocateRaw(
27     std::function<void*(size_t alignment, size_t num_bytes,
28                         bool verbose_failure)>
29         alloc_func,
30     int max_millis_to_wait, size_t alignment, size_t num_bytes) {
31   if (num_bytes == 0) {
32     LOG(WARNING) << "Request to allocate 0 bytes";
33     return nullptr;
34   }
35   uint64 deadline_micros = 0;
36   bool first = true;
37   void* ptr = nullptr;
38   while (ptr == nullptr) {
39     ptr = alloc_func(alignment, num_bytes, false);
40     if (ptr == nullptr) {
41       uint64 now = env_->NowMicros();
42       if (first) {
43         deadline_micros = now + max_millis_to_wait * 1000;
44         first = false;
45       }
46       if (now < deadline_micros) {
47         mutex_lock l(mu_);
48         WaitForMilliseconds(&l, &memory_returned_,
49                             (deadline_micros - now) / 1000);
50       } else {
51         return alloc_func(alignment, num_bytes, true);
52       }
53     }
54   }
55   return ptr;
56 }
57 
58 }  // namespace tensorflow
59