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::recursive_mutex * mtx,T * obj)30 LockedHandle(std::recursive_mutex* mtx, T* obj) : lock_(*mtx), obj_(obj) {} 31 LockedHandle() = default; // For the invalid case. 32 LockedHandle(LockedHandle&&) = default; 33 LockedHandle& operator=(LockedHandle&&) = default; 34 valid()35 bool valid() const { return obj_; } 36 explicit operator bool() const { return valid(); } 37 38 T* operator->() { 39 assert(valid()); 40 return obj_; 41 } 42 43 T& operator*() { return *(this->operator->()); } 44 45 private: 46 std::unique_lock<std::recursive_mutex> lock_; 47 T* obj_ = nullptr; 48 }; 49 50 } // namespace perfetto 51 52 #endif // INCLUDE_PERFETTO_TRACING_LOCKED_HANDLE_H_ 53