CodeBlanks Logo Icon CodeBlanks

threads.h

Learn standard threads with threads.h.

threads.h threads

The threads.h header is the standard thread library introduced in C11. thrd_create(&t, func, arg) starts a new thread; thrd_join(t, &result) waits for it.

This header also provides the mtx_t mutex type. mtx_lock(&m) locks it, mtx_unlock(&m) unlocks it. It is similar to POSIX pthread but is part of standard C, so it is portable. The thread function must have the signature int (*)(void *); its return value is retrieved via thrd_join.

The thread function

The thread function must have the signature int thread_func(void *arg). The arg parameter is passed via the third argument of thrd_create; its type is void *.

The function returns an int, retrieved via the second parameter of thrd_join. Returning thrd_success is conventional for success. If arg is unused, (void)arg; suppresses the unused-parameter warning. You can call printf inside the thread function; output ordering is guaranteed by thrd_join.

Practice Start a thread and join

Add #include <threads.h>. Write int thread_func(void *arg); suppress the warning with (void)arg;, print printf("İş parçacığı\n"), return 0;. In int main(void) declare thrd_t t;, call thrd_create(&t, thread_func, NULL) and thrd_join(t, NULL), then print printf("Bitti\n").

Starter code

main.c
#include <stdio.h>
#include <threads.h>

// parçacık fonksiyonu yaz
// başlat ve bekle
// main'de "Bitti" yazdır

Sample solution

main.c
#include <stdio.h>
#include <threads.h>

int thread_func(void *arg) {
    (void)arg;
    printf("İş parçacığı\n");
    return 0;
}

int main(void) {
    thrd_t t;
    thrd_create(&t, thread_func, NULL);
    thrd_join(t, NULL);
    printf("Bitti\n");
    return 0;
}

Expected output

İş parçacığı
Bitti

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Match the threads.h function

Term Meaning
thrd_create Start thread
thrd_join Wait thread
mtx_lock Lock
mtx_unlock Unlock

2 Which function starts a new thread?

  • thrd_create Correct answer
  • pthread_create
  • thread_create
  • _beginthread

Explanation: thrd_create is the thread-start function in threads.h.

3 Complete the thrd_join call

Question
thrd_create(&t, thread_func, NULL);
____(t, NULL);
Answer
thrd_create(&t, thread_func, NULL);
thrd_join(t, NULL);

Explanation: thrd_join(t, NULL) waits for the thread to finish.

All lessons in Expert