Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C

thrd_create — creating a thread

thrd_create starts func(arg) in a new thread and stores its identifier through thr. The call returns creation status, not the worker's result.

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

Syntax

#include <threads.h>
int thrd_create(thrd_t *thr, thrd_start_t func, void *arg);

thrd_create from <threads.h> creates a thread executing func(arg). thr points to storage for its identifier; func has a type compatible with int (*)(void *). The pointer arg is passed, not a copy of the pointed-to object.

The return value is thrd_success, thrd_nomem, or thrd_error. Returning from func is equivalent to thrd_exit with its result. Completion of thrd_create synchronizes with the new thread's beginning; it does not mean that its work has finished.

Keep argument data alive until its last use. Retrieve the result through thrd_join; if waiting is unnecessary, arrange thrd_detach. Thread creation alone does not protect later concurrent accesses to shared data.

In the example, input remains alive while waiting. Expected output assumes both operations succeed. A repository C23 compiler flag does not attest availability of a production thread runtime.

Examples

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

static int worker(void *arg)
{
    return *(const int *)arg + 1;
}

int main(void)
{
    thrd_t thread;
    static int input = 41;
    int result;

    if (thrd_create(&thread, worker, &input) != thrd_success) {
        return EXIT_FAILURE;
    }
    if (thrd_join(thread, &result) != thrd_success) {
        return EXIT_FAILURE;
    }

    printf("%d\n", result);
    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