1 /* Copyright 2019 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_CORE_PROFILER_LIB_PROFILER_LOCK_H_ 16 #define TENSORFLOW_CORE_PROFILER_LIB_PROFILER_LOCK_H_ 17 18 #include "tensorflow/core/platform/statusor.h" 19 20 namespace tensorflow { 21 namespace profiler { 22 23 // Handle for the profiler lock. At most one instance of this class, the 24 // "active" instance, owns the profiler lock. 25 class ProfilerLock { 26 public: 27 // Acquires the profiler lock if no other profiler session is currently 28 // active. 29 static StatusOr<ProfilerLock> Acquire(); 30 31 // Default constructor creates an inactive instance. 32 ProfilerLock() = default; 33 34 // Non-copyable. 35 ProfilerLock(const ProfilerLock&) = delete; 36 ProfilerLock& operator=(const ProfilerLock&) = delete; 37 38 // Movable. ProfilerLock(ProfilerLock && other)39 ProfilerLock(ProfilerLock&& other) 40 : active_(std::exchange(other.active_, false)) {} 41 ProfilerLock& operator=(ProfilerLock&& other) { 42 active_ = std::exchange(other.active_, false); 43 return *this; 44 } 45 ~ProfilerLock()46 ~ProfilerLock() { ReleaseIfActive(); } 47 48 // Allow creating another active instance. 49 void ReleaseIfActive(); 50 51 // Returs true if this is the active instance. Active()52 bool Active() const { return active_; } 53 54 private: 55 // Explicit constructor allows creating an active instance, private so it can 56 // only be called by Acquire. ProfilerLock(bool active)57 explicit ProfilerLock(bool active) : active_(active) {} 58 59 bool active_ = false; 60 }; 61 62 } // namespace profiler 63 } // namespace tensorflow 64 65 #endif // TENSORFLOW_CORE_PROFILER_LIB_PROFILER_LOCK_H_ 66