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 DistributedDB { TaskQueue(bool lockable)19TaskQueue::TaskQueue(bool lockable) 20 :lockable_(lockable) 21 {} 22 ~TaskQueue()23TaskQueue::~TaskQueue() 24 {} 25 PutTask(const Task & task)26void TaskQueue::PutTask(const Task &task) 27 { 28 if (!task) { 29 return; 30 } 31 tasks_.push(task); 32 } 33 GetTaskAutoLock()34Task TaskQueue::GetTaskAutoLock() 35 { 36 if (lockable_) { 37 std::thread::id thisId = std::this_thread::get_id(); 38 if (thisId != lockThread_) { 39 if (lockThread_ == std::thread::id()) { 40 lockThread_ = thisId; 41 } else { 42 return nullptr; 43 } 44 } 45 } 46 if (tasks_.empty()) { 47 ReleaseLock(); 48 return nullptr; 49 } 50 // copy and return 51 Task task = tasks_.front(); 52 tasks_.pop(); 53 return task; 54 } 55 ReleaseLock()56void TaskQueue::ReleaseLock() 57 { 58 if (!lockable_) { 59 return; 60 } 61 if (lockThread_ == std::this_thread::get_id()) { 62 lockThread_ = std::thread::id(); 63 } 64 } 65 IsEmptyAndUnlocked() const66bool TaskQueue::IsEmptyAndUnlocked() const 67 { 68 if (lockable_) { 69 if (lockThread_ != std::thread::id()) { 70 return false; 71 } 72 } 73 return tasks_.empty(); 74 } 75 CanGetTask() const76bool TaskQueue::CanGetTask() const 77 { 78 if (lockable_) { 79 if (lockThread_ != std::thread::id()) { 80 return false; 81 } 82 } 83 return !tasks_.empty(); 84 } 85 } // namespace DistributedDB 86