Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C

mtx_timedlock — lock a mutex with a deadline

`mtx_timedlock` attempts to lock a mutex by an absolute deadline based on `TIME_UTC`. It distinguishes successful acquisition, timeout, and error.

Version: C23; repository compiler flag, production runtime not attested

Syntax

#include <threads.h>
int mtx_timedlock(mtx_t *restrict mtx, const struct timespec *restrict ts);

mtx_timedlock from <threads.h> waits for a lock or the deadline ts: an absolute TIME_UTC time, not a waiting duration or monotonic time. The deadline does not guarantee an exact return time.

Initialize the mutex using mtx_init with mtx_timed or mtx_timed | mtx_recursive; mtx_plain alone is insufficient. Results are thrd_success, thrd_timedout, and thrd_error. Release the acquired lock with mtx_unlock only after success.

The example uses an unlocked mutex and sets the deadline one second after the sampled TIME_UTC timestamp. It does not force thread contention. Runtime support has not been attested.

Examples

#include <stdio.h>
#include <threads.h>
#include <time.h>

int main(void)
{
    mtx_t mutex;
    struct timespec deadline;

    if (mtx_init(&mutex, mtx_timed) != thrd_success)
        return 1;
    if (timespec_get(&deadline, TIME_UTC) != TIME_UTC) {
        mtx_destroy(&mutex);
        return 1;
    }

    deadline.tv_sec += 1;

    int result = mtx_timedlock(&mutex, &deadline);
    if (result == thrd_success) {
        if (mtx_unlock(&mutex) != thrd_success)
            return 1;
        puts("locked");
    } else if (result == thrd_timedout) {
        puts("timeout");
    } else {
        mtx_destroy(&mutex);
        return 1;
    }
    mtx_destroy(&mutex);
    return 0;
}

Result

locked

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources