1 /* 2 * Copyright (C) 2019 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 #ifndef INCLUDE_PERFETTO_TRACING_LOCKED_HANDLE_H_ 18 #define INCLUDE_PERFETTO_TRACING_LOCKED_HANDLE_H_ 19 20 #include <mutex> 21 22 namespace perfetto { 23 24 // This is used for GetDataSourceLocked(), in the (rare) case where the 25 // tracing code wants to access the state of its data source from the Trace() 26 // method. 27 template <typename T> 28 class LockedHandle { 29 public: LockedHandle(std::unique_lock<std::recursive_mutex> lock,T * obj)30 LockedHandle(std::unique_lock<std::recursive_mutex> lock, T* obj) 31 : lock_(std::move(lock)), obj_(obj) {} 32 LockedHandle() = default; // For the invalid case. 33 LockedHandle(LockedHandle&&) = default; 34 LockedHandle& operator=(LockedHandle&&) = default; 35 valid()36 bool valid() const { return obj_; } 37 explicit operator bool() const { return valid(); } 38 39 T* operator->() { 40 assert(valid()); 41 return obj_; 42 } 43 44 T& operator*() { return *(this->operator->()); } 45 46 private: 47 std::unique_lock<std::recursive_mutex> lock_; 48 T* obj_ = nullptr; 49 }; 50 51 } // namespace perfetto 52 53 #endif // INCLUDE_PERFETTO_TRACING_LOCKED_HANDLE_H_ 54