Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C

mtx_unlock — unlock a mutex

mtx_unlock from <threads.h> unlocks a mutex owned by the calling thread and returns a success or error code.

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

Syntax

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

mtx_unlock(mtx) unlocks the mutex pointed to by mtx. The argument must point to an initialized, still-existing mutex locked by the calling thread. Unlocking an unlocked mutex or one owned by another thread causes undefined behavior.

It returns thrd_success on success or thrd_error when the request cannot be honored. An error code does not replace compliance with the calling requirements. Unlocking synchronizes with a subsequent acquisition of the same mutex, providing visibility of protected writes.

The example uses one thread: it initializes the mutex, locks it, sets value, unlocks it, and destroys it. It demonstrates the lifecycle, not concurrent contention. Selecting C23 mode alone does not establish runtime thread-library availability.

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 = 42;

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

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

Result

42

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