Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C

mtx_trylock — attempt to lock a mutex without waiting

mtx_trylock attempts to acquire a mutex without waiting for its release. Its result distinguishes success, busy, and error.

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

Syntax

#include <threads.h>
int mtx_trylock(mtx_t *mtx);

mtx_trylock from <threads.h> takes a pointer to an initialized mtx_t. Unlike mtx_lock, it does not wait for a busy mutex to become available.

It returns thrd_success, thrd_busy, or thrd_error. In C23, the attempt may fail spuriously and return thrd_busy even if the mutex is unlocked.

Only success permits protected operations; call mtx_unlock afterward. Successful acquisition synchronizes with prior mtx_unlock calls on that mutex. Failure provides no such synchronization.

Examples

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

int main(void)
{
    mtx_t mutex;
    if (mtx_init(&mutex, mtx_plain) != thrd_success)
        return EXIT_FAILURE;

    int result = mtx_trylock(&mutex);
    if (result == thrd_success) {
        /* Protected work belongs here. */
        if (mtx_unlock(&mutex) != thrd_success)
            return EXIT_FAILURE;
    } else if (result != thrd_busy) {
        mtx_destroy(&mutex);
        return EXIT_FAILURE;
    }

    mtx_destroy(&mutex);
    puts("done");
    return EXIT_SUCCESS;
}

Result

done

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