Fishnet 2.0.1
Framework for Graph-Based Analysis of GIS Vector Data
Loading...
Searching...
No Matches
ThreadPool.hpp
Go to the documentation of this file.
1#include <thread>
2#include <vector>
3#include <queue>
4#include <mutex>
5#include <condition_variable>
6#include <functional>
8
9namespace fishnet::util{
11private:
12 std::vector<std::thread> threads;
13 std::queue<std::function<void()>> tasks;
14
15 std::mutex queueMutex;
16 std::condition_variable condition;
17 bool stop;
18public:
19 ThreadPool(size_t numThreads) : stop(false) {
20 if(numThreads == 0)
21 numThreads = 1;
22 for (size_t i = 0; i < numThreads; ++i) {
23 threads.emplace_back(
24 [this] {
25 while (true) {
26 std::function<void()> task;
27
28 {
29 std::unique_lock<std::mutex> lock(queueMutex);
30 condition.wait(lock, [this] { return stop || !tasks.empty(); });
31 if (stop && tasks.empty())
32 return;
33 task = std::move(tasks.front());
34 tasks.pop();
35 }
36
37 task();
38 }
39 }
40 );
41 }
42 }
43
44 template<fishnet::util::Task F>
45 void submit(F&& f) {
46 {
47 std::unique_lock<std::mutex> lock(queueMutex);
48 tasks.emplace(std::forward<F>(f));
49 }
50 condition.notify_one();
51 }
52
53 void join() {
54 if (stop)
55 return;
56 {
57 std::unique_lock<std::mutex> lock(queueMutex);
58 stop = true;
59 }
60 condition.notify_all();
61 for (std::thread& thread : threads)
62 thread.join();
63 }
64
66 join();
67 }
68};
69}
Definition ThreadPool.hpp:10
void submit(F &&f)
Definition ThreadPool.hpp:45
ThreadPool(size_t numThreads)
Definition ThreadPool.hpp:19
~ThreadPool()
Definition ThreadPool.hpp:65
void join()
Definition ThreadPool.hpp:53
Definition AlternativeKeyMap.hpp:4