tsandmann / freertos-teensy

FreeRTOS port with C++ std::thread support for ARM boards Teensy 3.5, 3.6, 4.0 and 4.1 (cortex-m4f and cortex-m7f)
95 stars 16 forks source link

Mutex Implementation #27

Closed yunusanr closed 4 months ago

yunusanr commented 4 months ago

Hello, This is my first time to use this library. Can you give me an example to implement mutex from this library? Is it the same as using free rtos for arduino? Thank you

yunusanr commented 4 months ago

I'm trying to use mutex like this code below

#include "arduino_freertos.h"
#include "avr/pgmspace.h"
#include "semphr.h"

SemaphoreHandle_t mutexes;
TaskHandle_t Task_1;
TaskHandle_t Task_2;

volatile int number1 = 1;
int number2 = 10;

volatile bool my_mutex = true;

static void task1(void *)
{
  while (true)
  {
    xSemaphoreTake(mutexes, portMAX_DELAY);
    for (int i = 0; i <= 5; i++)
    {
      Serial.println(number1);
      vTaskDelay(pdMS_TO_TICKS(500));
      number1 += 1;
    }
    Serial.println("task1");
    xSemaphoreGive(mutexes);
    // number1 = 1;
  }
}

static void task2(void *)
{
  while (true)
  {
    xSemaphoreTake(mutexes, portMAX_DELAY);
    for (int i = 0; i <= 5; i++)
    {
      Serial.println(number1);
      vTaskDelay(pdMS_TO_TICKS(500));
      number1 -= 1;
    }
    Serial.println("task2");
    xSemaphoreGive(mutexes);
  }
}

FLASHMEM __attribute__((noinline)) void setup()
{
  Serial.begin(115200);
  delay(3'000);

  if (CrashReport)
  {
    Serial.print(CrashReport);
    Serial.println();
    Serial.flush();
  }

  mutexes = xSemaphoreCreateMutex();

  if (mutexes == nullptr)
  {
    Serial.println("not mutex");
  }

  Serial.println(PSTR("\r\nBooting FreeRTOS kernel " tskKERNEL_VERSION_NUMBER ". Built by gcc " __VERSION__ " (newlib " _NEWLIB_VERSION ") on " __DATE__ ". ***\r\n"));

  xTaskCreate(task1, "task1", 100, nullptr, 1, &Task_1);
  xTaskCreate(task2, "task2", 100, nullptr, 1, &Task_2);

  Serial.println("setup(): starting scheduler...");
  Serial.flush();

  vTaskStartScheduler();
}

void loop() {}

And this is what I've got setup(): starting scheduler... 1 2 3 4 5 6 task1 7 8 9 10 11 12 task1 13 14 15 16 17 18 task1

output is not changing to task2

tsandmann commented 4 months ago

Hello,

The output is what I'd expect from your code. Both tasks have the same priority and try to hold the mutex all the time. Usually, you want to release the mutex (xSemaphoreGive()) before calling vTaskDelay() and take it back after.

To synchronize the calls to Serial.println(), you typically would do:

for (int i = 0; i <= 5; i++) {
    xSemaphoreTake(mutexes, portMAX_DELAY);
    Serial.println(number1);
    xSemaphoreGive(mutexes);
    vTaskDelay(pdMS_TO_TICKS(500));
    number1 -= 1;
}