Home | History | Annotate | Download | only in kernels
      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/kernels/initializable_lookup_table.h"
     17 
     18 #include "tensorflow/core/lib/core/errors.h"
     19 
     20 namespace tensorflow {
     21 namespace lookup {
     22 
     23 Status InitializableLookupTable::Find(OpKernelContext* ctx, const Tensor& keys,
     24                                       Tensor* values,
     25                                       const Tensor& default_value) {
     26   if (!is_initialized()) {
     27     return errors::FailedPrecondition("Table not initialized.");
     28   }
     29   // Do not let the use migrate before the check;  table is used without
     30   // a lock by the readers.
     31   std::atomic_thread_fence(std::memory_order_acquire);
     32   return DoFind(keys, values, default_value);
     33 }
     34 
     35 Status InitializableLookupTable::Initialize(InitTableIterator& iter) {
     36   if (!iter.Valid()) {
     37     return iter.status();
     38   }
     39   TF_RETURN_IF_ERROR(
     40       CheckKeyAndValueTensorsForInsert(iter.keys(), iter.values()));
     41 
     42   mutex_lock l(mu_);
     43   if (is_initialized()) {
     44     return errors::FailedPrecondition("Table already initialized.");
     45   }
     46 
     47   TF_RETURN_IF_ERROR(DoPrepare(iter.total_size()));
     48   while (iter.Valid()) {
     49     TF_RETURN_IF_ERROR(DoInsert(iter.keys(), iter.values()));
     50     iter.Next();
     51   }
     52   if (!errors::IsOutOfRange(iter.status())) {
     53     return iter.status();
     54   }
     55 
     56   // Prevent compiler/memory reordering of is_initialized and
     57   // the initialization itself.
     58   std::atomic_thread_fence(std::memory_order_release);
     59   is_initialized_ = true;
     60   return Status::OK();
     61 }
     62 
     63 }  // namespace lookup
     64 }  // namespace tensorflow
     65