SatDump 2.0.0-alpha-76a915210
Loading...
Searching...
No Matches
task_queue.h
1#pragma once
2
3#include <exception>
4#include <functional>
5#include <mutex>
6#include <queue>
7#include <thread>
8
9namespace satdump
10{
11 class TaskQueue
12 {
13 private:
14 std::thread task_thread;
15 std::mutex queue_mtx;
16 std::queue<std::function<void()>> task_queue;
17
18 bool thread_exited = true;
19
20 private:
21 void threadFunc()
22 {
23 recheck:
24 queue_mtx.lock();
25 bool queue_has_data = task_queue.size() > 0;
26 queue_mtx.unlock();
27
28 if (queue_has_data)
29 {
30 queue_mtx.lock();
31 auto task = task_queue.front();
32 task_queue.pop();
33 queue_mtx.unlock();
34
35 try
36 {
37 task();
38 }
39 catch (std::exception &e)
40 {
41 // TODOREWORK?
42 }
43
44 goto recheck;
45 }
46
47 thread_exited = true;
48 }
49
50 public:
51 TaskQueue() {}
52
53 ~TaskQueue()
54 {
55 if (task_thread.joinable())
56 task_thread.join();
57 }
58
59 void push(std::function<void()> task)
60 {
61 queue_mtx.lock();
62
63 task_queue.push(task);
64
65 if (thread_exited)
66 {
67 if (task_thread.joinable())
68 task_thread.join();
69 thread_exited = false;
70 task_thread = std::thread(&TaskQueue::threadFunc, this);
71 }
72
73 queue_mtx.unlock();
74 }
75 };
76} // namespace satdump