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 "logging.h"
15
16namespace pool
17{
18 ThreadPool::ThreadPool(const unsigned numThreads)
19 {
20 _workers.reserve(numThreads);
21 for (unsigned i = 0; i < numThreads; ++i)
22 {
23 _workers.emplace_back(
24 [this]
25 {
26 while (true)
27 {
28 Task task;
29 {
30 std::unique_lock lock(_queue_mutex);
31 _condition.wait(lock, [this] { return _stop || !_tasks.empty(); });
32 if (_stop && _tasks.empty())
33 {
34 return;
35 }
36 task = std::move(_tasks.front());
37 _tasks.pop();
38 }
39 try
40 {
41 task();
42 }
43 catch (const std::exception& e)
44 {
45 LOG(logging::Level::ERROR, "Exception in thread pool: {}", e.what());
46 }
47
48 {
49 std::unique_lock lock(_queue_mutex);
50 --_pending_tasks;
51 if (_pending_tasks == 0)
52 {
53 _done_condition.notify_all();
54 }
55 }
56 }
57 });
58 }
59 }
60
62 {
63 {
64 std::unique_lock lock(_queue_mutex);
65 _stop = true;
66 _condition.notify_all();
67 }
68 for (std::thread& worker : _workers)
69 {
70 worker.join();
71 }
72 }
73
75 {
76 std::unique_lock lock(_queue_mutex);
77 const unsigned active_threads = _pending_tasks;
78 const unsigned total_threads = _workers.size();
79 return total_threads > active_threads ? total_threads - active_threads : 0;
80 }
81}
~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.