In C11 there is a standard thread library, <threads.h>
, but no known compiler that yet implements it. Thus, to use multithreading in C you must use platform specific implementations such as the POSIX threads library (often referred to as pthreads) using the pthread.h
header.
Using threads can introduce extra undefined behavior such as a http://www.riptutorial.com/c/example/2622/data-race. For race-free access to variables that are shared between different threads C11 provides the mtx_lock()
mutex functionality or the (optional) http://www.riptutorial.com/c/topic/4924/atomics data-types and associated functions in stdatomic.h
.
#include <threads.h>
#include <stdio.h>
int run(void *arg)
{
printf("Hello world of C11 threads.");
return 0;
}
int main(int argc, const char *argv[])
{
thrd_t thread;
int result;
thrd_create(&thread, run, NULL);
thrd_join(&thread, &result);
printf("Thread return %d at the end\n", result);
}