Skip to content

Malloc fails when called inside thread #37

@VictorFSantolim

Description

@VictorFSantolim

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:

  • threads.threadsInfo() function is displaying incorrect stack bytes used/ remaining for thread 0 (main thread) and is not showing information for thread 2.
  • The malloc() inside thread 2 returns NULL after around 4kB have been allocated, despite having hundreds of kB left in the heap.
  • If I change the line "threads.addThread(thread_func2, 0, 8192);" to "threads.addThread(thread_func2);", it seems like the thread_func2 function is executed only once and than it crashes. However state of the thread remains as RUNNING.
#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:

  • Using malloc() inside the main thread works fine.
  • Changing the stack size of the threads and/or using a static global buffer instead of the head for the threads stack does modify when the malloc() problems starts to happens, but all combinations I tried still gave me errors.
  • If the thread is having problems with malloc, it is sometimes able to malloc successfully again after I use malloc in the loop.

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions