FERS 1.0.0
The Flexible Extensible Radar Simulator
Loading...
Searching...
No Matches
thread_pool.cpp
Go to the documentation of this file.
1// SPDX-License-Identifier: GPL-2.0-only
2//
3// Copyright (c) 2024-present FERS Contributors (see AUTHORS.md).
4//
5// See the GNU GPLv2 LICENSE file in the FERS project root for more information.
6
7/**
8 * @file thread_pool.cpp
9 * @brief A simple thread pool implementation.
10 */
11
12#include "thread_pool.h"
13
14#include <limits>
15#include <stdexcept>
16
17#include "logging.h"
18
19namespace pool
20{
21 ThreadPool::ThreadPool(const unsigned numThreads)
22 {
23 _workers.reserve(numThreads);
24 for (unsigned i = 0; i < numThreads; ++i)
25 {
26 _workers.emplace_back(
27 [this]
28 {
29 while (true)
30 {
31 Task task;
32 {
33 std::unique_lock lock(_queue_mutex);
34 _condition.wait(lock, [this] { return _stop || !_tasks.empty(); });
35 if (_stop && _tasks.empty())
36 {
37 return;
38 }
39 task = std::move(_tasks.front());
40 _tasks.pop();
41 }
42 try
43 {
44 task();
45 }
46 catch (const std::exception& e)
47 {
48 LOG(logging::Level::ERROR, "Exception in thread pool: {}", e.what());
49 }
50
51 {
52 std::unique_lock lock(_queue_mutex);
53 --_pending_tasks;
54 if (_pending_tasks == 0)
55 {
56 _done_condition.notify_all();
57 }
58 }
59 }
60 });
61 }
62 }
63
65 {
66 {
67 std::unique_lock lock(_queue_mutex);
68 _stop = true;
69 _condition.notify_all();
70 }
71 for (std::thread& worker : _workers)
72 {
73 worker.join();
74 }
75 }
76
78 {
79 std::unique_lock lock(_queue_mutex);
80 const unsigned active_threads = _pending_tasks;
81 if (_workers.size() > static_cast<std::size_t>(std::numeric_limits<unsigned>::max()))
82 {
83 throw std::runtime_error("Thread pool size exceeds unsigned range.");
84 }
85 const unsigned total_threads = static_cast<unsigned>(_workers.size());
86 return total_threads > active_threads ? total_threads - active_threads : 0;
87 }
88}
~ThreadPool()
Destroys the ThreadPool, joining all threads.
unsigned getAvailableThreads()
Returns the number of threads available for executing tasks.
ThreadPool(unsigned numThreads)
Constructs a ThreadPool with a specified number of threads.
Header file for the logging system.
#define LOG(level,...)
Definition logging.h:19
@ ERROR
Error level for error events.
A simple thread pool implementation.