0.5.4
C++ to UML diagram generator based on Clang
Loading...
Searching...
No Matches
thread_pool_executor.cc
Go to the documentation of this file.
1/**
2 * @file src/util/thread_pool_executor.cc
3 *
4 * Copyright (c) 2021-2024 Bartek Kryza <bkryza@gmail.com>
5 *
6 * Licensed under the Apache License, Version 2.0 (the "License");
7 * you may not use this file except in compliance with the License.
8 * You may obtain a copy of the License at
9 *
10 * http://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing, software
13 * distributed under the License is distributed on an "AS IS" BASIS,
14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 * See the License for the specific language governing permissions and
16 * limitations under the License.
17 */
18
20
21namespace clanguml::util {
22
24 : done_{false}
25{
26 if (pool_size == 0U)
27 pool_size = std::thread::hardware_concurrency();
28
29 for (auto i = 0U; i < pool_size; i++) {
30 threads_.emplace_back(&thread_pool_executor::worker, this);
31 }
32}
33
35
36std::future<void> thread_pool_executor::add(std::function<void()> &&task)
37{
38 std::unique_lock<std::mutex> l(tasks_mutex_);
39
40 std::packaged_task<void()> ptask{std::move(task)};
41 auto res = ptask.get_future();
42
43 tasks_.emplace_back(std::move(ptask));
44
45 l.unlock();
46 tasks_cond_.notify_one();
47
48 return res;
49}
50
52{
53 done_ = true;
54 for (auto &thread : threads_) {
55 if (thread.joinable())
56 thread.join();
57 }
58}
59
61{
62 try {
63 while (!done_) {
64 auto task = get();
65
66 task();
67 }
68 }
69 catch (std::runtime_error &e) {
70 }
71}
72
73std::packaged_task<void()> thread_pool_executor::get()
74{
75 std::unique_lock<std::mutex> l(tasks_mutex_);
76
77 while (tasks_.empty()) {
78 if (done_)
79 throw std::runtime_error("Thread pool closing...");
80
81 tasks_cond_.wait_for(l, std::chrono::seconds(1));
82 }
83
84 auto res = std::move(tasks_.front());
85 tasks_.pop_front();
86 return res;
87}
88
89} // namespace clanguml::util