1 /* Copyright 2021 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 #ifndef TENSORFLOW_LITE_DELEGATES_FLEX_SUBGRAPH_RESOURCE_H_ 16 #define TENSORFLOW_LITE_DELEGATES_FLEX_SUBGRAPH_RESOURCE_H_ 17 18 #include <memory> 19 #include <string> 20 21 #include "tensorflow/core/framework/resource_mgr.h" 22 #include "tensorflow/core/platform/mutex.h" 23 #include "tensorflow/core/platform/thread_annotations.h" 24 #include "tensorflow/lite/c/common.h" 25 #include "tensorflow/lite/core/subgraph.h" 26 27 namespace tflite { 28 namespace flex { 29 30 // This object stores a pointer for a TfLite subgraph and the associated mutex 31 // to access the subgraph. Before accessing the TF Lite subgraph, the caller 32 // needs to first acquire a lock on the mutex object. 33 class TFLiteSubgraphResource : public tensorflow::ResourceBase { 34 public: TFLiteSubgraphResource(Subgraph & subgraph,TfLiteDelegate * delegate)35 explicit TFLiteSubgraphResource(Subgraph& subgraph, TfLiteDelegate* delegate) 36 : subgraph_(subgraph), delegate_(delegate) {} 37 38 // This class is movable but not copyable. 39 TFLiteSubgraphResource(TFLiteSubgraphResource&&) = default; 40 TFLiteSubgraphResource& operator=(TFLiteSubgraphResource&&) = default; 41 42 TFLiteSubgraphResource(const TFLiteSubgraphResource&) = delete; 43 TFLiteSubgraphResource& operator=(TFLiteSubgraphResource&) = delete; 44 DebugString()45 std::string DebugString() const override { return "TFLiteSubgraphResource"; } 46 47 // Returns the TFLite subgraph. Before calling 48 // this method, the caller needs to acquire the underlying mutex lock. GetSubgraphResource()49 Subgraph& GetSubgraphResource() const TF_EXCLUSIVE_LOCKS_REQUIRED(mutex_) { 50 return subgraph_; 51 } 52 GetExclusiveLock()53 tensorflow::mutex& GetExclusiveLock() TF_LOCK_RETURNED(mutex_) { 54 return mutex_; 55 } 56 57 // Returns a pointer to the TfLiteDelegate which this instance of subgraph 58 // is running as part of it. GetFlexDelegate()59 TfLiteDelegate* GetFlexDelegate() TF_EXCLUSIVE_LOCKS_REQUIRED(mutex_) { 60 return delegate_; 61 } 62 63 private: 64 tensorflow::mutex mutex_; 65 Subgraph& subgraph_ TF_GUARDED_BY(mutex_); 66 TfLiteDelegate* delegate_ TF_GUARDED_BY(mutex_) = nullptr; 67 }; 68 69 } // namespace flex 70 } // namespace tflite 71 72 #endif // TENSORFLOW_LITE_DELEGATES_FLEX_SUBGRAPH_RESOURCE_H_ 73