Ardour  9.2-79-gba93f2fe52
thread_pool.h
Go to the documentation of this file.
1 /*
2  * Copyright (C) 2026 Robin Gareus <robin@gareus.org>
3  *
4  * This program is free software; you can redistribute it and/or modify
5  * it under the terms of the GNU General Public License as published by
6  * the Free Software Foundation; either version 2 of the License, or
7  * (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License along
15  * with this program; if not, write to the Free Software Foundation, Inc.,
16  * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
17  */
18 
19 #pragma once
20 
21 #include "pbd/libpbd_visibility.h"
22 
23 #include <condition_variable>
24 #include <functional>
25 #include <mutex>
26 #include <queue>
27 #include <thread>
28 
29 namespace PBD
30 {
32 {
33 public:
34  ThreadPool (size_t num_threads)
35  : _run (true)
36  {
37  for (size_t i = 0; i < num_threads; ++i) {
38  _threads.emplace_back ([this] {
39  while (true) {
40  std::function<void ()> task;
41  {
42  std::unique_lock<std::mutex> lock (_queue_lock);
43 
44  _trigger.wait (lock, [this] {
45  return !_queue.empty () || !_run;
46  });
47 
48  if (!_run && _queue.empty ()) {
49  return;
50  }
51 
52  task = std::move (_queue.front ());
53  _queue.pop ();
54  }
55 
56  task ();
57  }
58  });
59  }
60  }
61 
63  {
64  {
65  std::unique_lock<std::mutex> lock (_queue_lock);
66  _run = false;
67  }
68 
69  _trigger.notify_all ();
70 
71  for (auto& thread : _threads) {
72  thread.join ();
73  }
74  }
75 
76  void push (std::function<void ()> task)
77  {
78  {
79  std::unique_lock<std::mutex> lock (_queue_lock);
80  _queue.emplace (std::move (task));
81  }
82  _trigger.notify_one ();
83  }
84 
85 private:
86  std::vector<std::thread> _threads;
87  std::queue<std::function<void ()>> _queue;
88  std::mutex _queue_lock;
89  std::condition_variable _trigger;
90  bool _run;
91 };
92 
93 } // namespace PBD
std::vector< std::thread > _threads
Definition: thread_pool.h:86
ThreadPool(size_t num_threads)
Definition: thread_pool.h:34
std::mutex _queue_lock
Definition: thread_pool.h:88
void push(std::function< void()> task)
Definition: thread_pool.h:76
std::condition_variable _trigger
Definition: thread_pool.h:89
std::queue< std::function< void()> > _queue
Definition: thread_pool.h:87
#define LIBPBD_API
Definition: axis_view.h:42