</>EmbeddedInterview

Implement a wait with a timeout (condition variable).

Medium"Coding: Concurrency Primitives"
#include <errno.h>
#include <pthread.h>
#include <stdbool.h>
#include <time.h>

static pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER;
static pthread_cond_t  cv;
static bool data_ready;

void init_cv(void)
{
    pthread_condattr_t a;
    pthread_condattr_init(&a);
    pthread_condattr_setclock(&a, CLOCK_MONOTONIC);     /* immune to wall-clock changes */
    pthread_cond_init(&cv, &a);
}

/* returns true if data became ready, false on timeout */
bool wait_ready(unsigned timeout_ms)
{
    struct timespec deadline;
    clock_gettime(CLOCK_MONOTONIC, &deadline);
    deadline.tv_sec  += timeout_ms / 1000;
    deadline.tv_nsec += (long)(timeout_ms % 1000) * 1000000L;
    if (deadline.tv_nsec >= 1000000000L) { deadline.tv_sec++; deadline.tv_nsec -= 1000000000L; }

    pthread_mutex_lock(&m);
    int rc = 0;
    while (!data_ready && rc != ETIMEDOUT)
        rc = pthread_cond_timedwait(&cv, &m, &deadline);   /* absolute deadline: loop-safe */
    bool ok = data_ready;
    pthread_mutex_unlock(&m);
    return ok;
}

Points: use an absolute deadline computed once, so spurious wake-ups and retries do not extend the total wait; use CLOCK_MONOTONIC so NTP or user time changes do not break the timeout; normalise tv_nsec; after a timeout, still check the predicate (the event may have happened just at the deadline). RTOS equivalents take a timeout in ticks (xSemaphoreTake(sem, pdMS_TO_TICKS(100)), k_sem_take(&s, K_MSEC(100))); in bare-metal code, compare against a tick counter. Every wait in production code should have a timeout and a defined recovery.