C11 GCC threads.h 未找到?

31

以下代码

#include <threads.h>

给我报了这个错误:

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

使用最新的GCC和Clang,带有 -std=c11。

在GCC和Clang上不支持C11线程吗?还是有什么方法(或需要安装某些内容)可以获取它?我只是在使用来自Ubuntu存储库的gcc和clang软件包的Ubuntu14.04。


4
完全支持 C11 和/或 threads.h 的编译器数量是负数。 :( - this
3
C11线程,如果最终得到支持,将由C库而非编译器本身支持。至少有两个人正在讨论今年夏天将C11线程实现为glibc的GSoC项目。与此同时,您可能会发现pthread.h API非常相似,尽管每个函数和变量名都更长。 - zwol
5
很多标准化工作都是在“祝福”已经被广泛实现并被认为是好主意的扩展功能,但经验表明,在C语言标准中出现新功能和编译器/库实际广泛实现之间的领先时间更像是“10年至永远”,而不是“最多3年”。 - Emmet
8
@Emmet /我默默地将威士忌瓶沿着吧台推向你的方向 - zwol
显示剩余5条评论
5个回答

28

gcc文档的C11状态表明它不支持线程,它说:

线程[可选] | 库问题(未实现)

正如文档所指出的,这实际上不是一个gccclang的问题,而是一个glibc的问题。正如Zack指出的那样,看起来已经有工作正在进行中,以便将支持添加到glibc中,但这对您现在没有帮助。 在此期间,您可以使用这个

为glibc 2.28修复

根据Bug 14092-支持C11线程,这在glibc 2.28中得到了修复:

由上游实施:

9d0a979添加threads.h的手动文档
0a07288 nptl: 为ISO C11 threads添加测试用例
c6dd669 nptl: 为C11 threads添加abilist符号
78d4013 nptl: 添加C11 threads tss_*功能
918311a nptl: 添加C11 threads cnd_*功能
3c20a67 nptl: 添加C11 threads call_once功能
18d59c1 nptl: 添加C11 threads mtx_*功能
ce7528f nptl: 添加C11 threads thrd_*功能

它将包含在2.28中。


谢谢。那么GCC和Clang都不支持C11线程吗?那我就只能退回到POSIX线程了 :-( - lucasart
@lucasart 看起来是这样的。 - Shafik Yaghmour
1
我真希望昨天就读了这篇文章。glibc中的线程Bugzilla仍然未解决(已经2年了)。@lucasart:POSIX线程似乎几乎没有退化;接口几乎相同,“可移植”,并且已实现。:)事实上,编译glibc 2.19报告__STDC_NO_THREADS__1。另请参见此SO获取其他链接。它是pthreads(或C++11 std::thread,顺便说一下,它取决于-pthread...)。 - hoc_age
显然glibc方面有一些动态。 - Shafik Yaghmour
我现在可以在Glibc 2.31(Ubuntu 20.04)中使用#include <threads.h>了。 - Antti Haapala -- Слава Україні

6

Musl 支持 C11 <threads.h>

在 Debian 中安装 musl-tools,然后使用 musl-gcc 进行编译。我正在尝试使用 Musl 而不是 Glibc 来引导 Debian。

还可以参见这里


在Ubuntu中,链接的头文件c11threads.h会导致一堆错误。例如,PTHREAD_MUTEX_TIMED_NP未声明。搜索结果显示它应该在包含的pthreads.h中,但似乎并不是这样。 - Hi-Angel
1
@Hi-Angel 你需要使用 -std=gnu11 编译器标志代替 -std=c11,或者在包含 c11threads.h 文件之前使用 #define _GNU_SOURCE。 - nos
适用于Debian 9.13,2021年2月28日,星期日。 - zkutch

1

虽然C11线程尚未实现,但C++11线程已经实现,并且它们具有类似的功能。当然,如果C++11不可接受,那么关于POSIX线程的先前评论是您最好的选择。


1

线程已经合并到主流的Glibc中,例如在我的Ubuntu 20.04上可用。不幸的是,我似乎没有这个函数的手册页面。但是以下方法可以使用:

#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);
}

并测试它:

% 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

3
当使用C11标准线程时,为什么需要链接到pthread才能编译代码呢?这是有原因的吗? - dandev486

-1

你可以使用以下命令进行编译:

clang c-prog-with-threads_h.c

现在不使用-lpthread。(最新版本的编译器不需要指定std=c11,因为它是默认值)。

clang版本14.0.1,平台:Termux应用程序,Android。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接