1 /* 2 * Copyright (c) 2021 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 #include "task_queue.h" 17 18 namespace OHOS { 19 namespace NativePreferences { TaskQueue(bool lockable)20TaskQueue::TaskQueue(bool lockable) : lockable_(lockable) 21 { 22 } 23 ~TaskQueue()24TaskQueue::~TaskQueue() 25 { 26 } 27 PutTask(const Task & task)28void TaskQueue::PutTask(const Task &task) 29 { 30 if (!task) { 31 return; 32 } 33 tasks_.push(task); 34 } 35 GetTaskAutoLock()36Task TaskQueue::GetTaskAutoLock() 37 { 38 if (lockable_) { 39 std::thread::id thisId = std::this_thread::get_id(); 40 if (thisId != lockThread_) { 41 if (lockThread_ == std::thread::id()) { 42 lockThread_ = thisId; 43 } else { 44 return nullptr; 45 } 46 } 47 } 48 if (tasks_.empty()) { 49 ReleaseLock(); 50 return nullptr; 51 } 52 // copy and return 53 Task task = tasks_.front(); 54 tasks_.pop(); 55 return task; 56 } 57 ReleaseLock()58void TaskQueue::ReleaseLock() 59 { 60 if (!lockable_) { 61 return; 62 } 63 if (lockThread_ == std::this_thread::get_id()) { 64 lockThread_ = std::thread::id(); 65 } 66 } 67 IsEmptyAndUnlocked()68bool TaskQueue::IsEmptyAndUnlocked() 69 { 70 if (lockable_) { 71 if (lockThread_ != std::thread::id()) { 72 return false; 73 } 74 } 75 return tasks_.empty(); 76 } 77 } // namespace NativePreferences 78 } // namespace OHOS 79