Since C11
, C
provides standard thread APIs like what C++
does. It means technically, you should use C
‘s standard thread APIs to do multi-thread stuff, not pthread
APIs. Below is a simple example:
#include <threads.h>
#include <stdio.h>
int print_thread(void* s)
{
printf("%s\n", (char*)s);
thrd_exit(0);
}
int main()
{
thrd_t tid;
if (thrd_success != thrd_create(&tid, print_thread, "Hello world"))
{
fprintf(stderr, "Create thread error\n");
return 1;
}
thrd_join(tid, NULL);
return 0;
}
Check thrd_create implementation in glibc
:
#include "thrd_priv.h"
int
thrd_create (thrd_t *thr, thrd_start_t func, void *arg)
{
_Static_assert (sizeof (thr) == sizeof (pthread_t),
"sizeof (thr) != sizeof (pthread_t)");
int err_code = __pthread_create_2_1 (thr, ATTR_C11_THREAD,
(void* (*) (void*))func, arg);
return thrd_err_map (err_code);
}
You can see thrd_create
just encapsulates __pthread_create_2_1
, so you can guess in glibc
, the standard C
thread APIs are just wrappers of pthread
implementation. It means you need to link pthread
library during compiling. Otherwise you will meet following errors:
main.c:(.text+0x1e): undefined reference to `thrd_exit'
......
main.c:(.text+0x4f): undefined reference to `thrd_create'
/usr/bin/ld: main.c:(.text+0x60): undefined reference to `thrd_join'
P.S., the full code is here.