Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C

mtx_lock — locking a mutex

mtx_lock waits to acquire a mutex. It returns thrd_success on success or thrd_error on failure.

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

Syntax

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

mtx_lock from <threads.h> blocks until it acquires the mutex pointed to by mtx. Successfully initialize it with mtx_init first. After success, execute the critical section, then call mtx_unlock.

Do not call this function again for a non-recursive mutex already owned by the calling thread: that is undefined behavior, not a guaranteed error. Earlier unlocks of the same mutex synchronize with its acquisition.

The example uses one thread to demonstrate the mutex lifecycle, not thread contention. Selecting C23 mode alone does not attest to thread support in the runtime library.

Examples

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

int main(void)
{
    mtx_t mutex;
    int value = 0;

    if (mtx_init(&mutex, mtx_plain) != thrd_success)
        return EXIT_FAILURE;

    if (mtx_lock(&mutex) != thrd_success) {
        mtx_destroy(&mutex);
        return EXIT_FAILURE;
    }

    ++value;

    if (mtx_unlock(&mutex) != thrd_success)
        abort();

    mtx_destroy(&mutex);
    printf("%d\n", value);
    return EXIT_SUCCESS;
}

Result

1

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