diff --git a/apps/09_binary_semaphore/CMakeLists.txt b/apps/09_binary_semaphore/CMakeLists.txt new file mode 100644 index 0000000..e8723cb --- /dev/null +++ b/apps/09_binary_semaphore/CMakeLists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.20.0) + +find_package(Zephyr REQUIRED HINTS $ENV{ZEPHYR_BASE}) + +project(09_binary_semaphore) + +target_sources(app PRIVATE src/main.c) \ No newline at end of file diff --git a/apps/09_binary_semaphore/prj.conf b/apps/09_binary_semaphore/prj.conf new file mode 100644 index 0000000..287c27b --- /dev/null +++ b/apps/09_binary_semaphore/prj.conf @@ -0,0 +1,4 @@ +CONFIG_SERIAL=y +CONFIG_CONSOLE=y +CONFIG_PRINTK=y +CONFIG_THREAD_NAME=y \ No newline at end of file diff --git a/apps/09_binary_semaphore/src/main.c b/apps/09_binary_semaphore/src/main.c new file mode 100644 index 0000000..8af9c47 --- /dev/null +++ b/apps/09_binary_semaphore/src/main.c @@ -0,0 +1,212 @@ +#include +#include +#include +#include + +#define STACK_SIZE 1024 +#define THREAD_PRIORITY 5 + +// Thread A timing (ms) +#define A_WORK_MS 150 +#define A_PAUSE_MS 50 + +// Thread B timing (ms) +#define B_WORK_MS 120 +#define B_WAIT_MS 100 +#define B_PAUSE_MS 40 +#define B_RETRY_MS 20 + +/* Create a binary semaphore with: + * Initial count = 1 (resource initially available) + * Maximum count = 1 (only one token exists) + * + * Count = 1: Resource available + * Count = 0: Resource occupied + */ +K_SEM_DEFINE(key_sem, 1, 1); + +/* Atomic counter used only to verify mutual exclusion. + * + * Expected values: + * 0: No thread is inside the shared resource + * 1: Exactly one thread is inside + * + * A value greater than 1 indicates a synchronization error. + */ +static atomic_t in_room = ATOMIC_INIT(0); + +/* ===================================================== + * Thread Objects and Stacks + * ===================================================== */ +static struct k_thread thread_a; +static struct k_thread thread_b; + +K_THREAD_STACK_DEFINE(stack_a, STACK_SIZE); +K_THREAD_STACK_DEFINE(stack_b, STACK_SIZE); + +/* Simulate accessing a shared resource. + * + * IMPORTANT: + * The caller must acquire key_sem before calling this function. + * The caller must release key_sem afterward. + * + * k_msleep() simulates time spent using the resource. + * The calling thread sleeps but continues holding the semaphore. + */ +static void use_shared_resource(const char *name, + int32_t duration_ms) { + + // Increment occupancy and obtain its previous value + atomic_val_t previous = atomic_inc(&in_room); + + // Detect a mutual-exclusion violation + if (previous != 0) { + printk("[%s] ERROR: Multiple occupants!\n", name); + } + + printk("[%s] ENTER (resource acquired)\n", name); + + // Simulate work while holding the semaphore + k_msleep(duration_ms); + + printk("[%s] EXIT (resource work completed)\n", name); + + // Mark this thread as no longer using the resource + atomic_dec(&in_room); +} + +// Thread A +static void thread_a_entry(void *p1, void *p2, void *p3) { + + ARG_UNUSED(p1); + ARG_UNUSED(p2); + ARG_UNUSED(p3); + + printk("[A] Started (K_FOREVER)\n"); + + while (1) { + + /* Wait indefinitely for the semaphore. + * + * If count == 1: + * Acquire immediately and decrement count to 0. + * + * If count == 0: + * Block until the semaphore becomes available. + */ + int ret = k_sem_take(&key_sem, K_FOREVER); + + if (ret != 0) { + printk("[A] Semaphore take failed: %d\n", ret); + continue; + } + + // Semaphore successfully acquired. + use_shared_resource("A", A_WORK_MS); + + /* Release semaphore after leaving the resource. + * Another waiting thread may now acquire it. + */ + k_sem_give(&key_sem); + + // Perform non-critical work outside the resource. + k_msleep(A_PAUSE_MS); + } +} + +// Thread B +static void thread_b_entry(void *p1, void *p2, void *p3) { + + ARG_UNUSED(p1); + ARG_UNUSED(p2); + ARG_UNUSED(p3); + + printk("[B] Started (timeout = %d ms)\n", B_WAIT_MS); + + while (1) { + + /* Attempt to acquire the semaphore. + * + * If available: + * Return 0 immediately. + * + * If unavailable: + * Wait up to B_WAIT_MS milliseconds. + * + * On timeout: + * Return -EAGAIN. + */ + int ret = k_sem_take(&key_sem, K_MSEC(B_WAIT_MS)); + + if (ret == 0) { + + // Semaphore successfully acquired + use_shared_resource("B", B_WORK_MS); + + // Release the semaphore + k_sem_give(&key_sem); + + // Non-critical work outside the resource + k_msleep(B_PAUSE_MS); + + } else if (ret == -EAGAIN) { + + // Semaphore acquisition timed out + printk("[B] Semaphore timeout (%d ms)\n", B_WAIT_MS); + + k_msleep(B_RETRY_MS); + + } else { + + // Unexpected error + printk("[B] Semaphore take failed: %d\n", ret); + + k_msleep(B_RETRY_MS); + } + } +} + +int main(void) { + + printk("\n[MAIN] Binary Semaphore Example\n"); + printk("[MAIN] One resource shared by two threads\n"); + + /* Create Thread A in an inactive state + * + * K_FOREVER as the start delay means the thread + * will not execute until k_thread_start() is called. + */ + k_thread_create( + &thread_a, + stack_a, + K_THREAD_STACK_SIZEOF(stack_a), + thread_a_entry, + NULL, NULL, NULL, + THREAD_PRIORITY, + 0, + K_FOREVER + ); + + // Create Thread B in an inactive state + k_thread_create( + &thread_b, + stack_b, + K_THREAD_STACK_SIZEOF(stack_b), + thread_b_entry, + NULL, NULL, NULL, + THREAD_PRIORITY, + 0, + K_FOREVER + ); + + // Assign names before starting the threads + (void)k_thread_name_set(&thread_a, "THREAD_A"); + (void)k_thread_name_set(&thread_b, "THREAD_B"); + + // Make both threads eligible for scheduling + k_thread_start(&thread_a); + k_thread_start(&thread_b); + + return 0; + +} \ No newline at end of file