Arduino DLNA Server
Loading...
Searching...
No Matches
TaskLinux.h
Go to the documentation of this file.
1// Linux Task implementation using std::thread to mimic FreeRTOS Task API
2#pragma once
3#ifdef USE_CPP_TASK
4
5#include <atomic>
6#include <chrono>
7#include <condition_variable>
8#include <functional>
9#include <mutex>
10#include <thread>
11
12namespace tiny_dlna {
13
18class TaskLinux {
19 public:
20 TaskLinux(const char *name, int stackSize, int priority = 1, int core = -1) {
21 (void)name;
22 (void)stackSize;
23 (void)priority;
24 (void)core; // parameters unused
25 }
26 TaskLinux() = default;
27
28 ~TaskLinux() { remove(); }
29
30 bool create(const char *name, int stackSize, int priority = 1,
31 int core = -1) {
32 (void)name;
33 (void)stackSize;
34 (void)priority;
35 (void)core; // parameters unused
36 return true;
37 }
38
39 bool begin(std::function<void()> process) {
40 if (running_thread.joinable()) return false; // already running
41 loop_code = process;
42 terminate_flag = false;
43 // start suspended similar to FreeRTOS create+suspend pattern
44 paused = false;
45 running_thread = std::thread([this] { this->thread_loop(); });
46 return true;
47 }
48
49 void end() { remove(); }
50
51 void remove() {
52 terminate_flag = true;
53 resume(); // wake if paused
54 if (running_thread.joinable()) {
55 if (std::this_thread::get_id() == running_thread.get_id()) {
56 // Avoid deadlock: cannot join the current thread; detach instead
57 running_thread.detach();
58 } else {
59 running_thread.join();
60 }
61 }
62 }
63
64 void suspend() {
65 std::lock_guard<std::mutex> lk(mtx);
66 paused = true;
67 }
68
69 void resume() {
70 {
71 std::lock_guard<std::mutex> lk(mtx);
72 paused = false;
73 }
74 cv.notify_all();
75 }
76
77 // API compatibility – return thread id reference surrogate
78 std::thread::id &getTaskHandle() { return thread_id; }
79
80 void setReference(void *r) { ref = r; }
81 void *getReference() { return ref; }
82
83 protected:
84 std::thread running_thread;
85 std::thread::id thread_id{};
86 std::function<void()> loop_code = nop;
87 void *ref = nullptr;
88 std::atomic<bool> terminate_flag{false};
89 std::mutex mtx;
90 std::condition_variable cv;
91 bool paused = false;
92
93 static void nop() {
94 std::this_thread::sleep_for(std::chrono::milliseconds(100));
95 }
96
97 void thread_loop() {
98 thread_id = std::this_thread::get_id();
99 while (!terminate_flag.load()) {
100 // wait while paused
101 {
102 std::unique_lock<std::mutex> lk(mtx);
103 cv.wait(lk, [this] { return !paused || terminate_flag.load(); });
104 }
105 if (terminate_flag.load()) break;
106 if (loop_code)
107 loop_code();
108 else
109 nop();
110 }
111 }
112};
113
114using Task = TaskLinux;
115
116
117} // namespace audio_tools
118
119#endif // __linux__
Definition: Allocator.h:13
TaskRTOS Task
Definition: TaskRTOS.h:117