I created this library because I needed three threads and I needed two of them to run at a precise time no matter what the others were doing. The first thread handled serial communication. The second was running a Kalman filter using float matrix multiplication with the Eigen library. And the third was a fast current control loop thread which had to be able to interrupt the matrix calculations.
When should you use this library:
- When you need your Arduino to do multiple things at once. Especially when you have some code that takes a long time to execute and some that need to run often.
- When you want a clean and easy to use C++11 interface to create threads with lambda functions.
- When you want to avoid pre-allocating thread stack sizes.
The library with documentation and example code can be found at:
(https://bitbucket.org/adamb3_14/threadhandler/src/master)
For more in-depth details see the README file.
How it worksEach cyclic thread has a priority and a period. If a thread, with higher priority than the current executing thread, reaches its next execution time the scheduler will pause the current thread and switch to the higher priority one. Once the high priority thread completes its execution the scheduler switches back to the previous thread.
The scheduling scheme of the ThreadHandler library is as follows:
1) Highest priority first.
2) If the priority is the same then the thread with the earliest deadline is executed first.
3) If two threads have the same deadline then the first created thread will execute first.
4) A thread can only be interrupted by threads with higher priority.
5) Once a thread is executing it will block execution for all threads with lower priority until the run function returns.
6) The loop function has priority -128 compared to ThreadHandler threads.
How to useThreads can be created via c++ inheritance
class MyThread : public Thread
{
public:
MyThread() : Thread(priority, period, offset){}
virtual ~MyThread(){}
virtual void run()
{
//code to run
}
};
Or via createThread and a lambda function
Thread* myThread = createThread(priority, period, offset,
[]()
{
//code to run
});
Thread objects automatically connect to the ThreadHandler when they are created.
To start execution of created thread objects call:
ThreadHandler::getInstance()->enableThreadExecution();
Recommended knowledgeTo use this library without problem you should know c++ and have some knowledge about multithreaded programing and thread safety.
Comments
Please log in or sign up to comment.