2 * Copyright (c) 2020 Samsung Electronics Co., Ltd All Rights Reserved
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
22 template <typename Task>
24 using lock_t = std::unique_lock<std::mutex>;
28 std::condition_variable _ready;
31 bool try_pop(Task &task)
33 lock_t lock{_mutex, std::try_to_lock};
34 if (!lock || _q.empty()) return false;
35 task = std::move(_q.front());
40 bool try_push(Task &&task)
43 lock_t lock{_mutex, std::try_to_lock};
44 if (!lock) return false;
45 _q.push_back(std::move(task));
63 while (_q.empty() && !_done) _ready.wait(lock);
64 if (_q.empty()) return false;
65 task = std::move(_q.front());
70 void push(Task &&task)
74 _q.push_back(std::move(task));
89 const unsigned _count{std::thread::hardware_concurrency()};
90 std::vector<std::thread> _threads;
91 std::vector<TaskQueue<shared_task>> _q{_count};
92 std::atomic<unsigned> _index{0};
100 for (unsigned n = 0; n != _count * 2; ++n) {
101 if (_q[(i + n) % _count].try_pop(task)) {
107 if (!success && !_q[i].pop(task)) break;
115 for (unsigned n = 0; n != _count; ++n) {
116 _threads.emplace_back([&, n] { run(n); });
121 for (auto &e : _q) e.done();
123 for (auto &e : _threads) e.join();
128 static Executor& instance() {
129 static Executor singleton;
133 void post(shared_task task)
139 for (unsigned n = 0; n != _count; ++n) {
140 if (_q[(i + n) % _count].try_push(std::move(task))) return;
144 _q[i % _count].push(std::move(task));
149 void async(shared_task task)
151 Executor::instance().post(std::move(task));