FreeRTOS stuck at prvCheckTasksWaitingTermination - delay

I'm working with a Nucleo-STm32F767 and I had generated the code with CubeMX including FreeRTOS 9.
My code has 5 task and each task has a loop, where the task is suspended on each iteration.
while( 1 )
{
//Do something
osDelay(TASK_MAIN_DELAY_MS);
}
At this point my system works well.
Now I added a task that handle the communication with an SPI network controller. The network controller has it own middleware written in C.
Now every time I try to suspend a task (with osDelay) my code is stucked into prvCheckTasksWaitingTermination and my system is blocked forever.
static void prvCheckTasksWaitingTermination( void )
{
/** THIS FUNCTION IS CALLED FROM THE RTOS IDLE TASK **/
#if ( INCLUDE_vTaskDelete == 1 )
{
BaseType_t xListIsEmpty;
/* ucTasksDeleted is used to prevent vTaskSuspendAll() being called
too often in the idle task. */
while( uxDeletedTasksWaitingCleanUp > ( UBaseType_t ) 0U )
{
vTaskSuspendAll();
{
xListIsEmpty = listLIST_IS_EMPTY( &xTasksWaitingTermination );
}
( void ) xTaskResumeAll();
if( xListIsEmpty == pdFALSE )
{
TCB_t *pxTCB;
taskENTER_CRITICAL();
{
pxTCB = ( TCB_t * ) listGET_OWNER_OF_HEAD_ENTRY( ( &xTasksWaitingTermination ) );
( void ) uxListRemove( &( pxTCB->xStateListItem ) );
--uxCurrentNumberOfTasks;
--uxDeletedTasksWaitingCleanUp;
}
taskEXIT_CRITICAL();
prvDeleteTCB( pxTCB );
}
else
{
mtCOVERAGE_TEST_MARKER();
}
}
}
#endif /* INCLUDE_vTaskDelete */
In particular, the execution is stopped here: while( uxDeletedTasksWaitingCleanUp > ( UBaseType_t ) 0U ) becuase uxDeletedTasksWaitingCleanUp is equal to 0.
I don't know how to resolve this issue :(
Anybody can help me?
Thanks and best regards,
Federico

prvCheckTaskWaitingTermination is just part of the idle task. Unless you are running tickless operation it will just keep executing as long as no higher priority tasks are able to run. In your case I'm going to guess that the SPI driver is doing something that stops or masks the tick interrupt so time doesn't change, so delays never end. Just a guess though.

I'm not sure if this will help your issue, but I was running into this same problem and was able to get past it.
In my freertos.cpp file, I had several tasks executing in succession one after another. However, the second task was being executed but would fail each time because the peripheral it was trying to use was not working properly. It seems that since I did not have a catch for this, it was having trouble switching from the task.
Once I fixed the peripheral (in my case a cellular modem that was trying to connect to an unreachable server), the program executed properly and did not get stuck in this prvCheckTasksWaitingTermination function.
So, in your case, perhaps this indicates an issue with your SPI configuration that needs attention.
I hope this helps.

Related

pthread_mutex_lock() always returns EINVAL with PTHREAD_PRIO_PROTECT mutex even with ceiling properly defined

So I'm working on a multi-process real-time application on Linux and there are a few operations we have protected by Mutexes. I'm attempting to switch our mutexes to the PTHREAD_PRIO_PROTECT protocol, but I must be missing something, as I always get EINVAL on the pthread_mutex_lock() calls.
All of the below code uses similar error reporting checks. I'll just mark that with // Error Reporting to simplify the code listings. Each has some variant of the following blob:
{
char message[256];
throw std::runtime_error( std::string("Error locking Mutex: ") +
strerror_r( errno, message, sizeof(message) ) );
}
Here's the basic mutex initialization code, setting a ceiling of 40:
pthread_mutex_t thelock;
pthread_mutexattr_t attrib;
pthread_mutexattr_init(&attrib);
if ( pthread_mutexattr_setprotocol(&attrib, PTHREAD_PRIO_PROTECT) )
{
// Error Reporting
}
if ( pthread_mutexattr_setprioceiling(&attrib, 40) )
{
// Error Reporting
}
pthread_mutex_init(&thelock, &attrib);
Setting the schedule on the current thread with a priority of 20 (well below ceiling):
struct sched_param param;
param.sched_priority = 20;
if ( -1 == sched_setscheduler(0, SCHED_FIFO, &param) )
{
// Error Reporting
}
I also tried threads with no explicit scheduler set, and setting the scheduler/parameter on the thread attribute before creation.
No matter which way I do it, I end up with EINVAL for the following code:
if ( pthread_mutex_lock(&thelock) )
{
// Error Reporting
}
I've set the capabilities on my test program before running so it is able to properly change priorities:
sudo setcap 'cap_sys_nice=eip' threadpriotest
So it appears my previous testing was in error; I forgot to use pthread_attr_setinheritsched(&threaddr, PTHREAD_EXPLICIT_SCHED) when I changed the priority of the first thread that claimed the mutex. The method of using sched_setscheduler() does work, but I wasn't using that on the first thread at the time.
The bottom line is that it appears the thread must already be using SCHED_FIFO before the mutex will work with PTHREAD_PRIO_PROTECT. This is contrary to PTHREAD_PRIO_INHERIT, which seems to work fine with non-FIFO threads.

Terminating a thread CMSIS-RTOS

I'm currently trying to make my device (STM32F105) which is usually running 12 threads on CMSIS RTOS go to low power mode. In order to simplify the algorythm I think (definitely not sure) that it's a good idea to terminate all the threads using osThreadTerminate and after a wake up recreate them using osThreadCreate
void os_idle_demon (void) {
/* The idle demon is a system thread, running when no other thread is */
/* ready to run. */
for (;;) {
/* HERE: include optional user code to be executed when no thread runs.*/
if (Sleep.SleepEnabled == 1)
{
if (Sleep.IsSleeping == 1)
{
// __wfi();
// PWR_EnterSTOPMode(PWR_Regulator_ON, PWR_STOPEntry_WFI); //PWR_Regulator_LowPower
__nop();
// osDelay(5000);
if (Sleep.WakeUp)
{
Sleep.IsSleeping = 0;
WakeUp();
// SetSysClock();
Sleep.WakeUp = 0;
Sleep.SleepEnabled = 0;
Sleep.TimeTillSleep = 60;
}
}
else
{
if (Sleep.TimeTillSleep == 0 )
{
TerminateTasks();
ResetPeripherals();
Sleep.IsSleeping = 1;
// PWR_EnterSTANDBYMode();
// __wfi();
// PWR_EnterSTOPMode(PWR_Regulator_ON, PWR_STOPEntry_WFI);
__nop();
// osDelay(5000);
}
}
}
}
}
As you can see I use some global variables to determinte when to sleep. TerminateTasks(); is used to terminate all of my running threads using osThreadTerminate function which doesn't seem to cause any trouble, but after I call WakeUp(); which uses osThreadCreate function to recreate terminated threads I run into an os stack overflow. So there are a few questions I struggle to find answers to. Does osThreadTerminate command in CMSIS-RTOS release stack after execution? Is there a better way to go into a low power mode ? I hope I made my point clear, if there's a need to be more specific let me know. Would be grateful if you shared your experience with similar problems.
Do you use dynamic allocation in your other thread ? Because if so, killing your thread when there are running could result in memory leak.

How to kill a thread from another thread in vala

I have a main thread which creates another thread to perform some job.
main thread has a reference to that thread. How do I kill that thread forcefully some time later, even if thread is still operating. I cant find a proper function call that does that.
any help would be appreciable.
The original problem that I want to solve is I created a thread a thread to perform a CPU bound operation that may take 1 second to complete or may be 10 hours. I cant predict how much time it is going to take. If it is taking too much time, I want it to gracefully abandon the job when/ if I want. can I somehow communicate this message to that thread??
Assuming you're talking about a GLib.Thread, you can't. Even if you could, you probably wouldn't want to, since you would likely end up leaking a significant amount of memory.
What you're supposed to do is request that the thread kill itself. Generally this is done by using a variable to indicate whether or not it has been requested that the operation stop at the earliest opportunity. GLib.Cancellable is designed for this purpose, and it integrates with the I/O operations in GIO.
Example:
private static int main (string[] args) {
GLib.Cancellable cancellable = new GLib.Cancellable ();
new GLib.Thread<int> (null, () => {
try {
for ( int i = 0 ; i < 16 ; i++ ) {
cancellable.set_error_if_cancelled ();
GLib.debug ("%d", i);
GLib.Thread.usleep ((ulong) GLib.TimeSpan.MILLISECOND * 100);
}
return 0;
} catch ( GLib.Error e ) {
GLib.warning (e.message);
return -1;
}
});
GLib.Thread.usleep ((ulong) GLib.TimeSpan.SECOND);
cancellable.cancel ();
/* Make sure the thread has some time to cancel. In an application
* with a UI you probably wouldn't need to do this artificially,
* since the entire application probably wouldn't exit immediately
* after cancelling the thread (otherwise why bother cancelling the
* thread? Just exit the program) */
GLib.Thread.usleep ((ulong) GLib.TimeSpan.MILLISECOND * 150);
return 0;
}

Does Arduino support threading?

I have a couple of tasks to do with arduino but one of them takes very long time, so I was thinking to use threads to run them simultaneously.
I have an Arduino Mega
[Update]
Finally after four years I can install FreeRTOS in my arduino mega. Here is a link
In short: NO.
But you may give it a shot at:
http://www.kwartzlab.ca/2010/09/arduino-multi-threading-librar/
(Archived version: https://web.archive.org/web/20160505034337/http://www.kwartzlab.ca/2010/09/arduino-multi-threading-librar
Github: https://github.com/jlamothe/mthread
Not yet, but I always use this Library with big projects:
https://github.com/ivanseidel/ArduinoThread
I place the callback within a Timer interrupt, and voilá! You have pseudo-threads running on the Arduino...
Just to make this thread more complete: there are also protothreads which have very small memory footprint (couple bytes if I remember right) and preserve variables local to thread; very handy and time saving (far less finite state machines -> more readable code).
Examples and code:
arduino-class / ProtoThreads wiki
Just to let you know what results you may expect: serial communication # 153K6 baudrate with threads for: status diodes blinking, time keeping, requested functions evaluation, IO handling and logic and all on atmega328.
Not real threading but TimedActions are a good alternative for many uses
http://playground.arduino.cc/Code/TimedAction#Example
Of course, if one task blocks, the others will too, while threading can let one task freeze and the others will continue...
No you can't but you can use Timer interrupt.
Ref : https://www.teachmemicro.com/arduino-timer-interrupt-tutorial/
The previous answer is correct, however, the arduino generally runs pretty quick, so if you properly time your code, it can accomplish tasks more or less simultaneously.
The best practice is to make your own functions and avoid putting too much real code in the default void loop
You can use arduinos
It is designed for Arduino environment. Features:
Only static allocation (no malloc/new)
Support context switching when delaying execution
Implements semaphores
Lightweight, both cpu and memory
I use it when I need to receive new commands from bluetooth/network/serial while executing the old ones and the old ones have delay in them.
One thread is the sever thread that does the following loop:
while (1) {
while ((n = Serial.read()) != -1) {
// do something with n, like filling a buffer
if (command_was_received) {
arduinos_create(command_func, arg);
}
}
arduinos_yield(); // context switch to other threads
}
The other is the command thread that executes the command:
int command_func(void* arg) {
// move some servos
arduinos_delay(1000); // wait for them to move
// move some more servos
}
Arduino does not support multithread programming.
However there have been some workarounds, for example the one in this project (you can install it also from the Arduino IDE).
It seems you have to define the schedule time yourself while in a real multithread environment it is the OS that decides when to execute tasks.
Alternatively you can use protothreads
The straight answer is No No No!. There are some alternatives but you can't expect a perfect multi threading functionality from an arduino mega. You can use arduino due or lenado for multithreading like below-
void loop1(){
}
void loop2(){
}
void loop3(){
}
Normally, I handle those types of cases in backend. You can run the main code in a server while using Arduino to just collect inputs and show outputs. In such cases I would prefer nodemcu which has built in wifi.
Thread NO!
Concurrent YES!
You can run different tasks concurrently with FreeRTOS library.
https://www.arduino.cc/reference/en/libraries/freertos/
void TaskBlink( void *pvParameters );
void TaskAnalogRead( void *pvParameters );
// Now set up two tasks to run independently.
xTaskCreate(
TaskBlink
, (const portCHAR *)"Blink" // A name just for humans
, 128 // Stack size
, NULL
, 2 // priority
, NULL );
xTaskCreate(
TaskAnalogRead
, (const portCHAR *) "AnalogRead"
, 128 // This stack size can be checked & adjusted by reading Highwater
, NULL
, 1 // priority
, NULL );
void TaskBlink(void *pvParameters) // This is a task.
{
(void) pvParameters;
// initialize digital pin 13 as an output.
pinMode(13, OUTPUT);
for (;;) // A Task shall never return or exit.
{
digitalWrite(13, HIGH); // turn the LED on (HIGH is the voltage level)
vTaskDelay( 1000 / portTICK_PERIOD_MS ); // wait for one second
digitalWrite(13, LOW); // turn the LED off by making the voltage LOW
vTaskDelay( 1000 / portTICK_PERIOD_MS ); // wait for one second
}
}
void TaskAnalogRead(void *pvParameters) // This is a task.
{
(void) pvParameters;
// initialize serial communication at 9600 bits per second:
Serial.begin(9600);
for (;;)
{
// read the input on analog pin 0:
int sensorValue = analogRead(A0);
// print out the value you read:
Serial.println(sensorValue);
vTaskDelay(1); // one tick delay (15ms) in between reads for stability
}
}
Just take care!
When different tasks tried to reach variables at the same time, like i2c communication line or sd card module. Use Semaphores and mutexes
https://www.geeksforgeeks.org/mutex-vs-semaphore/.
Arduino does not supports threading. However, you can do the next best thing and structure your code around state machines running in interleaving.
While there are lots of ways to implement your tasks as state machines, I recommend this library (https://github.com/Elidio/StateMachine). This library abstracts most of the process.
You can create a state machine as a class like this:
#include "StateMachine.h"
class STATEMACHINE(Blink) {
private:
int port;
int waitTime;
CREATE_STATE(low);
CREATE_STATE(high);
void low() {
digitalWrite(port, LOW);
*this << &STATE(high)<< waitTime;
}
void high() {
digitalWrite(port, HIGH);
*this << &STATE(low)<< waitTime;
}
public:
Blink(int port = 0, int waitTime = 0) :
port(port),
waitTime(waitTime),
INIT_STATE(low),
INIT_STATE(high)
{
pinMode(port, OUTPUT);
*this << &STATE(low);
}
};
The macro STATEMACHINE() abstracts the class inheritances, the macro CREATE_STATE() abstracts the state wrapper creation, the macro INIT_STATE() abstracts method wrapping and the macro STATE() abstracts state wrapper reference within the state machine class.
State transition is abstracted by << operator between the state machine class and the state, and if you want a delayed state transition, all you have to do is to use that operator with an integer, where the integer is the delay in millisseconds.
To use the state machine, first you have to instantiate it. Declaring an reference to the class in global space while instantiating it with new on setup function might do the trick
Blink *led1, *led2, *led3;
void setup() {
led1 = new Blink(12, 300);
led2 = new Blink(11, 500);
led3 = new Blink(10, 700);
}
Then you run the states on loop.
void loop() {
(*led2)();
(*led1)();
(*led3)();
}

Problem waking up multiple threads using condition variable API in win32

I have a problem in understanding how the winapi condition variables work.
On the more specific side, what I want is a couple of threads waiting on some condition. Then I want to use the WakeAllConditionVariable() call to wake up all the threads so that they can do work. Besides the fact that i just want the threads started, there isn't any other prerequisite for them to start working ( like you would have in an n producer / n consumer scenario ).
Here's the code so far:
#define MAX_THREADS 4
CONDITION_VARIABLE start_condition;
SRWLOCK cond_rwlock;
bool wake_all;
__int64 start_times[MAX_THREADS];
Main thread:
int main()
{
HANDLE h_threads[ MAX_THREADS ];
int tc;
for (tc = 0; tc < MAX_THREADS; tc++)
{
DWORD tid;
h_threads[tc] = CreateThread(NULL,0,(LPTHREAD_START_ROUTINE)thread_routine,(void*)tc,0,&tid);
if( h_threads[tc] == NULL )
{
cout << "Error while creating thread with index " << tc << endl;
continue;
}
}
InitializeSRWLock( &cond_rwlock );
InitializeConditionVariable( &start_condition );
AcquireSRWLockExclusive( &cond_rwlock );
// set the flag to true, then wake all threads
wake_all = true;
WakeAllConditionVariable( &start_condition );
ReleaseSRWLockExclusive( &cond_rwlock );
WaitForMultipleObjects( tc, h_threads, TRUE, INFINITE );
return 0;
}
And here is the code for the thread routine:
DWORD thread_routine( PVOID p_param )
{
int t_index = (int)(p_param);
AcquireSRWLockShared( &cond_rwlock );
// main thread sets wake_all to true and calls WakeAllConditionVariable()
// so this thread should start doing the work (?)
while ( !wake_all )
SleepConditionVariableSRW( &start_condition,&cond_rwlock, INFINITE,CONDITION_VARIABLE_LOCKMODE_SHARED );
QueryPerformanceCounter((LARGE_INTEGER*)&start_times[t_index]);
// do the actual thread related work here
return 0;
}
This code does not do what i would expect it to do. Sometimes just one thread finishes the job, sometimes two or three, but never all of them. The main function never gets past the WaitForMultipleObjects() call.
I'm not exactly sure what I've done wrong, but I would assume some synchronization issue somewhere ?
Any help would be appreciated. (sorry if I re-posted older topic with different dressing :)
You initialize the cond_rwlock and start_condition variables too late. Move the code up, before you start the threads. A thread is likely to start running right away, especially on a multi-core machine.
And test the return values of api functions. You don't know why it doesn't work because you never check for failure.

Resources