Frage

The following code

#include <threads.h>

Gives me this error:

fatal error: threads.h: No such file or directory

Using the latest GCC and Clang with -std=c11.

Is C11 threading not supported by GCC and Clang? Or is there a hack (or something to install) to get it? I'm just using Ubuntu 14.04 with the gcc and clang packages from the Ubuntu repo.

War es hilfreich?

Lösung

The gcc document C11 status indicates that it does not support threading, it says:

Threading [Optional] | Library issue (not implemented)

As the document indicates this is not really a gcc or clang issue but glibc issue. As Zack pointed out it looks like there may be work under way soon to get support for this into glibc but that won't help you now. You can use this in the meantime.

Fixed for glibc 2.28

According the Bug 14092 - Support C11 threads this is fixed in glibc 2.28:

Implemented upstream by:

9d0a979 Add manual documentation for threads.h
0a07288 nptl: Add test cases for ISO C11 threads
c6dd669 nptl: Add abilist symbols for C11 threads
78d4013 nptl: Add C11 threads tss_* functions
918311a nptl: Add C11 threads cnd_* functions
3c20a67 nptl: Add C11 threads call_once functions
18d59c1 nptl: Add C11 threads mtx_* functions
ce7528f nptl: Add C11 threads thrd_* functions

It will be included in 2.28.

Andere Tipps

Musl support C11 <threads.h>.

In Debian install musl-tools, and then compile with musl-gcc. I am working on bootstrapping Debian with Musl instead of Glibc.

Also see this.

While C11 threads has not been implemented yet, C++11 threads have been implemented and they have similar functionality. Of course, C++11 may be an unacceptable solution, in which case the prior comments about POSIX threads are your best hope.

Threads have been merged into mainline Glibc and are available for example on my Ubuntu 20.04. Unfortunately I don't seem to have any manual pages for the function. But this works:

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

int hello_from_threading(void *arg) {
    printf("Thread about to take a nap...\n");
    thrd_sleep(&(struct timespec) { .tv_sec = 3 }, NULL);
    printf("Woke up from 3 second slumber\n");
    return 42;
}

int main(void) {
    thrd_t thread;
    thrd_create(&thread, hello_from_threading, NULL);
    int res;
    printf("A thread was started\n");
    thrd_join(thread, &res);
    printf("Thread ended, returning %d\n", res);
}

and testing it:

% gcc threading.c -o threading -lpthread
% ./threading
A thread was started
Thread about to take a nap...
Woke up from 3 second slumber
Thread ended, returning 42

You can compile it with the command;

clang c-prog-with-threads_h.c

without using -lpthread now. (And latest versions of compilers did not need to specify std=c11, because of it is default).

clang version 14.0.1, platform: Termux app, Android.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top