rusEFI
The most advanced open source ECU
Loading...
Searching...
No Matches
thread_controller.h
Go to the documentation of this file.
1/**
2 * @file thread_controller.h
3 *
4 * @date Jan 5, 2019
5 * @author Matthew Kennedy, (c) 2019
6 */
7
8#pragma once
9
10/**
11 * @brief A base class for a controller that requires its own thread.
12 *
13 * Inherit from ThreadController. Implement ThreadTask with the logic required for your thread.
14 * The template parameter specifies the size of the stack used for the thread. (because we have to
15 * allocate the stack at compile time, it has to be a template parameter instead of a normal parameter)
16 */
17template <int TStackSize>
18class ThreadController : public chibios_rt::BaseStaticThread<TStackSize>
19{
20private:
21 const tprio_t m_prio;
22 /* TODO: use ref instead of m_started */
23 bool m_started = false;
24 chibios_rt::ThreadReference ref;
25
26protected:
27 // Override this function to implement your controller's thread's behavior.
28 virtual void ThreadTask() = 0;
29
30 void main() override {
31 this->setName(m_name);
32
33 ThreadTask();
34 }
35
36 const char* const m_name;
37
38public:
39 ThreadController(const char* name, tprio_t priority)
40 : m_prio(priority)
41 , m_name(name)
42 {
43 }
44
45 using chibios_rt::BaseStaticThread<TStackSize>::start;
46
47 /**
48 * @brief Start the thread.
49 */
50 void start()
51 {
52 if (!m_started)
53 {
54 m_started = true;
55 ref = chibios_rt::BaseStaticThread<TStackSize>::start(m_prio);
56 }
57 }
58
59 /**
60 * @brief Request thread termination and waits for termination
61 *
62 * Thread should periadicaly execute something like:
63 * if (chThdShouldTerminateX())
64 * chThdExit((msg_t)0x0);
65 */
66 void stop()
67 {
68 if (m_started) {
69 /* Asking for thread termination.*/
70 ref.requestTerminate();
71
72 /* Waiting for termination, releasing the reference.*/
73 ref.wait();
74
75 m_started = false;
76 }
77 }
78};
A base class for a controller that requires its own thread.
virtual void ThreadTask()=0
ThreadController(const char *name, tprio_t priority)
void start()
Start the thread.
const char *const m_name
const tprio_t m_prio
void stop()
Request thread termination and waits for termination.
chibios_rt::ThreadReference ref
void main() override