以下代码
#include <threads.h>
给我报了这个错误:
fatal error: threads.h: No such file or directory
使用最新的GCC和Clang,带有 -std=c11。
在GCC和Clang上不支持C11线程吗?还是有什么方法(或需要安装某些内容)可以获取它?我只是在使用来自Ubuntu存储库的gcc和clang软件包的Ubuntu14.04。
以下代码
#include <threads.h>
给我报了这个错误:
fatal error: threads.h: No such file or directory
使用最新的GCC和Clang,带有 -std=c11。
在GCC和Clang上不支持C11线程吗?还是有什么方法(或需要安装某些内容)可以获取它?我只是在使用来自Ubuntu存储库的gcc和clang软件包的Ubuntu14.04。
gcc
文档的C11状态表明它不支持线程,它说:
线程[可选] | 库问题(未实现)
正如文档所指出的,这实际上不是一个gcc
或clang
的问题,而是一个glibc
的问题。正如Zack指出的那样,看起来已经有工作正在进行中,以便将支持添加到glibc
中,但这对您现在没有帮助。
在此期间,您可以使用这个。
根据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中。
glibc
中的线程Bugzilla仍然未解决(已经2年了)。@lucasart:POSIX线程似乎几乎没有退化;接口几乎相同,“可移植”,并且已实现。:)事实上,编译glibc
2.19报告__STDC_NO_THREADS__
为1
。另请参见此SO获取其他链接。它是pthreads(或C++11 std::thread
,顺便说一下,它取决于-pthread
...)。 - hoc_age#include <threads.h>
了。 - Antti Haapala -- Слава УкраїніPTHREAD_MUTEX_TIMED_NP
未声明。搜索结果显示它应该在包含的pthreads.h
中,但似乎并不是这样。 - Hi-Angel虽然C11线程尚未实现,但C++11线程已经实现,并且它们具有类似的功能。当然,如果C++11不可接受,那么关于POSIX线程的先前评论是您最好的选择。
线程已经合并到主流的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
你可以使用以下命令进行编译:
clang c-prog-with-threads_h.c
现在不使用-lpthread。(最新版本的编译器不需要指定std=c11,因为它是默认值)。
clang版本14.0.1,平台:Termux应用程序,Android。
pthread.h
API非常相似,尽管每个函数和变量名都更长。 - zwol