Simple multithread (main+2 threads) code raising out of memory error

I am trying to create two threads in addition to main just to see how it works. If I create only one and control the last variable from the button callback, program works. If I create two, like below, I get Operator new out of memory error directly at the start. What is the reason for this ? The board is NUCLEO F072RB.

#include "mbed.h"

DigitalOut led1(LED1);
InterruptIn button1(BUTTON1);

Thread thread1;
Thread thread2;

uint32_t last;

void fThread1() {

  printf("T1\n");

  while (true) {

    led1 = !led1;
    if (last == 1) {
      ThisThread::sleep_for(100ms);
    } else {
      ThisThread::sleep_for(500ms);
    }

  }

}

void fThread2() {

  printf("T2\n");

  while (true) {

    ThisThread::flags_wait_any(0x01);
    printf("change\n");
    last = (last == 1) ? 2 : 1;

  }

}

void fButton() {
  thread2.flags_set(0x01);
  //last = (last == 1) ? 2 : 1;
} 

int main()
{

  printf("S\n");

  last = 1;

  thread1.start(callback(fThread1));
  thread2.start(callback(fThread2));

  button1.mode(PullNone);
  button1.rise(callback(fButton));

  printf("L\n");

  while (true);

  return 0;

}

Ahoj,

that is problem of resources maybe? Your board have only 16KB of SRAM and the full MbedOS functionally need a lot of resources.

The bare metal profile (no RTOS functionality) is optimal for this memory size with Mbed.

BR, Jan

I think thats true, the default stacksize is 4 k, in total 12 k for main + 2 threads.
The thread constructor has overloads where a reduced stacksize can be supplied, but with 16 k its not fun.
Bare Metal and events maybe a better solution.

I need to pay attention to numbers more :slight_smile: Thanks @JohnnyK

Thanks @JojoS, I will try reducing the stack size just for the sake of trying but then try bare metal profile or another board.

Just to confirm, the issue is definitely due to resources. I tried the same code on a different board (256K ram) and it works with no issues.

1 Like