// Nama : I Gede Bagus Jayendra
// NIM : 5311422096
#include <Arduino_FreeRTOS.h>
#include <semphr.h> // Include semaphore library
// Globals
static int shared_var = 0;
SemaphoreHandle_t mutex; // Mutex to control access to shared_var
//*****************************************************************************
// Tasks
// Increment shared variable (the right way with mutex)
void incTask(void *parameters) {
// Loop forever
while (1) {
// Attempt to take the mutex before accessing shared_var
if (xSemaphoreTake(mutex, portMAX_DELAY) == pdPASS) {
// Critical section
shared_var++; // Increment directly
vTaskDelay(random(100, 500) / portTICK_PERIOD_MS); // Simulate delay
// Print out the new shared variable
Serial.println(shared_var);
// Release the mutex after done modifying shared_var
xSemaphoreGive(mutex);
}
vTaskDelay(1); // Yield to allow other tasks to run
}
}
//*****************************************************************************
// Main
void setup() {
// Hack to kinda get randomness
randomSeed(analogRead(0));
// Configure Serial
Serial.begin(9600);
Serial.println();
Serial.println("---FreeRTOS Race Condition Demo with Mutex---");
// Create the mutex before using it
mutex = xSemaphoreCreateMutex();
if (mutex == NULL) {
Serial.println("Gagal membuat mutex");
while (1); // Stop execution if mutex creation failed
}
// Start task 1
xTaskCreate(incTask,
"Increment Task 1",
192,
NULL,
1,
NULL);
// Start task 2
xTaskCreate(incTask,
"Increment Task 2",
192,
NULL,
1,
NULL);
}
void loop() {
// Execution should never get here
}