| 1 |
/* |
| 2 |
* Copyright (C) 2015 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 |
#include "JobQueue.h" |
| 18 |
|
| 19 |
JobQueue::Job JobQueue::pop() { |
| 20 |
Job job; |
| 21 |
std::lock_guard<std::mutex> lock(m_lock); |
| 22 |
if (!m_queue.empty()) { |
| 23 |
std::swap(job, m_queue.front()); |
| 24 |
m_queue.pop_front(); |
| 25 |
} |
| 26 |
return job; |
| 27 |
} |
| 28 |
|
| 29 |
void JobQueue::enqueue(JobQueue::Job&& job) { |
| 30 |
std::lock_guard<std::mutex> lock(m_lock); |
| 31 |
m_queue.push_back(std::forward<JobQueue::Job>(job)); |
| 32 |
} |
| 33 |
|
| 34 |
bool JobQueue::runJobIfAny() { |
| 35 |
Job job(pop()); |
| 36 |
// call the job without holding our lock |
| 37 |
if (job) { |
| 38 |
job(); |
| 39 |
return true; |
| 40 |
} |
| 41 |
return false; |
| 42 |
} |
| 43 |
|
| 44 |
void JobQueue::runAllJobs() { |
| 45 |
std::deque<Job> q; |
| 46 |
std::unique_lock<std::mutex> lock(m_lock); |
| 47 |
std::swap(q, m_queue); |
| 48 |
lock.unlock(); |
| 49 |
for (auto& job : q) { |
| 50 |
job(); |
| 51 |
} |
| 52 |
} |
| 53 |
|
| 54 |
bool JobQueue::isEmpty() const { |
| 55 |
std::lock_guard<std::mutex> lock(m_lock); |
| 56 |
return m_queue.empty(); |
| 57 |
} |