1 /* Copyright 2016 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/framework/op_kernel.h" 17 #include "tensorflow/core/framework/tensor.h" 18 #include "tensorflow/core/platform/mutex.h" 19 20 namespace tensorflow { 21 22 // This Op takes in a list of strings and a counter (ref). It increments the 23 // counter by 1 and returns the element at that position in the list (circling 24 // around if need to). 25 class ObtainNextOp : public OpKernel { 26 public: 27 explicit ObtainNextOp(OpKernelConstruction* context) : OpKernel(context) {} 28 29 void Compute(OpKernelContext* ctx) override { 30 const Tensor* list; 31 OP_REQUIRES_OK(ctx, ctx->input("list", &list)); 32 int64 num_elements = list->NumElements(); 33 auto list_flat = list->flat<string>(); 34 35 // Allocate output. 36 Tensor* output_tensor = nullptr; 37 OP_REQUIRES_OK(ctx, ctx->allocate_output("out_element", TensorShape({}), 38 &output_tensor)); 39 40 // Obtain mutex for the "counter" tensor. 41 mutex* mu; 42 OP_REQUIRES_OK(ctx, ctx->input_ref_mutex("counter", &mu)); 43 mutex_lock l(*mu); 44 // Increment "counter" tensor by 1. 45 Tensor counter_tensor; 46 OP_REQUIRES_OK(ctx, ctx->mutable_input("counter", &counter_tensor, true)); 47 int64* pos = &counter_tensor.scalar<int64>()(); 48 *pos = (*pos + 1) % num_elements; 49 50 // Assign value to output. 51 output_tensor->scalar<string>()() = list_flat(*pos); 52 } 53 }; 54 55 REGISTER_KERNEL_BUILDER(Name("ObtainNext").Device(DEVICE_CPU), ObtainNextOp); 56 57 } // namespace tensorflow 58