Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C

thrd_detach — detaching a thread

thrd_detach from <threads.h> arranges thread-resource reclamation after termination. It neither waits for termination nor stops the thread.

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

Syntax

#include <threads.h>
int thrd_detach(thrd_t thr);

thrd_detach(thr) detaches a thread: its resources are reclaimed after termination. It returns thrd_success, or thrd_error when the request cannot be honored.

The thread must not already have been detached or joined using thrd_join. After successful detachment, do not call thrd_join for it. Detachment replaces neither synchronization nor data-lifetime management.

The example ends the main thread through thrd_exit(0), rather than ending the program by returning from main. This lets the worker finish. Support for <threads.h> is optional; __STDC_NO_THREADS__ signals its absence. A C23 flag does not attest runtime-library availability.

Examples

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

static int worker(void *arg)
{
    (void)arg;
    puts("worker finished");
    return 0;
}

int main(void)
{
    thrd_t thread;
    if (thrd_create(&thread, worker, NULL) != thrd_success) {
        return EXIT_FAILURE;
    }

    if (thrd_detach(thread) != thrd_success) {
        (void)thrd_join(thread, NULL);
        return EXIT_FAILURE;
    }

    thrd_exit(0);
}

Result

worker finished

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