ftrias / TeensyThreads

MIT License
184 stars 26 forks source link

Malloc fails when called inside thread #37

Open VictorFSantolim opened 2 years ago

VictorFSantolim commented 2 years ago

I am having multiple issues using the TeensyThreads library with Teensy 3.5 using PlatformIO Teensy 4.15.0 platform (Teensyduino v1.55).

The following minimum reproducible example below shows some of the issues I am facing:

#include <Arduino.h>
#include <TeensyThreads.h>

#define SIZE_ALLOC 200
uint32_t bytes_alloc = 0;

void thread_func1()
{
  while(1)
  {
    // Do stuff
  }
}

void thread_func2()
{
  while(1)
  {
    char* pointer = (char*)malloc(SIZE_ALLOC);
    if(pointer)
    {
      bytes_alloc += SIZE_ALLOC;
      Serial.printf("Allocated %d bytes on the heap. Addr = %p . Total bytes allocated = %d\n", SIZE_ALLOC, pointer, bytes_alloc);
    }
    else
    {
      Serial.printf("Failed to allocate %d bytes on the heap!\n" , SIZE_ALLOC);
    }
    threads.delay(1000);
  }
}

void setup()
{
  Serial.begin(9600);
  delay(5000);
  threads.addThread(thread_func1);
  threads.addThread(thread_func2, 0, 8192);
}

void loop() 
{
  threads.delay(10000);
  Serial.println(threads.threadsInfo()); // Information for thread 0 is incorrect, information for thread 2 is missing
}

I have experimented with multiple variations of this code and my conclusions so far were:

What am I missing here? I know that the use of malloc is not encouraged in micro controllers, and in my full code I am taking all precautions needed to avoid head fragmentation, monitoring the use of memory,etc. The problems I presented here, however, doesn't seem to be related to this.

VictorFSantolim commented 2 years ago

I have performed more tests, now using Arduino IDE 1.8.19 and newest Teensyduino 1.57. Results: