1 /* 2 * Copyright (c) 2023 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 16 #ifndef FFRT_TS_QUEUE_HPP 17 #define FFRT_TS_QUEUE_HPP 18 #include <queue> 19 #include <mutex> 20 #include <condition_variable> 21 22 namespace ffrt { 23 // 线程安全队列,支持线程阻塞 24 template <typename T> 25 class TSQueue { 26 public: 27 TSQueue() = default; 28 ~TSQueue() = default; 29 Push(const T & data)30 void Push(const T& data) 31 { 32 { 33 std::lock_guard<decltype(mutex_)> lg(mutex_); 34 queue_.push(data); 35 } 36 cond_.notify_one(); 37 } 38 Pop()39 T Pop() 40 { 41 std::unique_lock<decltype(mutex_)> lg(mutex_); 42 cond_.wait(lg, [this] { return !queue_.empty(); }); 43 auto& res = queue_.front(); 44 queue_.pop(); 45 return res; 46 } 47 48 private: 49 std::queue<T> queue_; 50 std::mutex mutex_; 51 std::condition_variable cond_; 52 }; 53 } // namespace ffrt 54 #endif 55