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 #include "tensorflow/core/profiler/lib/profiler_lock.h" 16 17 #include <atomic> 18 19 #include "tensorflow/core/platform/errors.h" 20 #include "tensorflow/core/platform/macros.h" 21 #include "tensorflow/core/platform/statusor.h" 22 #include "tensorflow/core/util/env_var.h" 23 24 namespace tensorflow { 25 namespace profiler { 26 namespace { 27 28 // Track whether there's an active profiler session. 29 // Prevents another profiler session from creating ProfilerInterface(s). 30 std::atomic<int> g_session_active = ATOMIC_VAR_INIT(0); 31 32 // g_session_active implementation must be lock-free for faster execution of 33 // the ProfilerLock API. 34 static_assert(ATOMIC_INT_LOCK_FREE == 2, "Assumed atomic<int> was lock free"); 35 36 } // namespace 37 Acquire()38/*static*/ StatusOr<ProfilerLock> ProfilerLock::Acquire() { 39 // Use environment variable to permanently lock the profiler. 40 // This allows running TensorFlow under an external profiling tool with all 41 // built-in profiling disabled. 42 static bool tf_profiler_disabled = [] { 43 bool disabled = false; 44 ReadBoolFromEnvVar("TF_DISABLE_PROFILING", false, &disabled).IgnoreError(); 45 return disabled; 46 }(); 47 if (TF_PREDICT_FALSE(tf_profiler_disabled)) { 48 return errors::AlreadyExists( 49 "TensorFlow Profiler is permanently disabled by env var " 50 "TF_DISABLE_PROFILING."); 51 } 52 int already_active = g_session_active.exchange(1, std::memory_order_acq_rel); 53 if (already_active) { 54 return errors::AlreadyExists("Another profiling session active."); 55 } 56 return ProfilerLock(/*active=*/true); 57 } 58 ReleaseIfActive()59void ProfilerLock::ReleaseIfActive() { 60 if (active_) { 61 g_session_active.store(0, std::memory_order_release); 62 active_ = false; 63 } 64 } 65 66 } // namespace profiler 67 } // namespace tensorflow 68