1 /** 2 * Copyright (c) 2021-2024 Huawei Device Co., Ltd. 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 PANDA_RUNTIME_TOOLING_SAMPLER_LOCK_FREE_QUEUE_H 16 #define PANDA_RUNTIME_TOOLING_SAMPLER_LOCK_FREE_QUEUE_H 17 18 #include <atomic> 19 #include <memory> 20 #include "runtime/tooling/sampler/sample_info.h" 21 22 namespace ark::tooling::sampler { 23 24 class LockFreeQueue { 25 public: 26 // NOLINTNEXTLINE(cppcoreguidelines-pro-type-member-init) LockFreeQueue()27 LockFreeQueue() 28 { 29 std::atomic<Node *> dummyNode = new Node(std::make_unique<FileInfo>(), nullptr); 30 // Atomic with relaxed order reason: there is no data race 31 head_.store(dummyNode, std::memory_order_relaxed); 32 // Atomic with relaxed order reason: there is no data race 33 tail_.store(dummyNode, std::memory_order_relaxed); 34 size_ = 0; 35 } 36 ~LockFreeQueue()37 ~LockFreeQueue() 38 { 39 FileInfo module; 40 while (size_ != 0) { 41 Pop(module); 42 } 43 delete head_; 44 } 45 46 void Push(const FileInfo &data); 47 bool FindValue(uintptr_t data) const; 48 Size()49 size_t Size() 50 { 51 return size_; 52 } 53 54 NO_MOVE_SEMANTIC(LockFreeQueue); 55 NO_COPY_SEMANTIC(LockFreeQueue); 56 57 private: 58 // NOLINTNEXTLINE(performance-unnecessary-value-param) 59 void Pop(FileInfo &ret); 60 61 private: 62 struct Node { 63 // NOLINTBEGIN NodeNode64 Node(std::unique_ptr<FileInfo> new_data, std::atomic<Node *> new_next) : data(std::move(new_data)) 65 { 66 // Atomic with relaxed order reason: there is no data race 67 next.store(new_next, std::memory_order_relaxed); 68 } 69 // NOLINTEND 70 71 // NOLINTBEGIN(misc-non-private-member-variables-in-classes) 72 std::unique_ptr<FileInfo> data; 73 std::atomic<Node *> next; 74 // NOLINTEND(misc-non-private-member-variables-in-classes) 75 }; 76 77 std::atomic<Node *> head_; 78 std::atomic<Node *> tail_; 79 std::atomic<size_t> size_; 80 }; 81 82 } // namespace ark::tooling::sampler 83 84 #endif // PANDA_RUNTIME_TOOLING_SAMPLER_LOCK_FREE_QUEUE_H 85