C11 atomics 最小可运行示例
通过在 glibc 2.28 中添加线程,我们可以在纯 C11 中执行原子和线程。
示例来自:https ://en.cppreference.com/w/c/language/atomic
主程序
#include <stdio.h>
#include <threads.h>
#include <stdatomic.h>
atomic_int acnt;
int cnt;
int f(void* thr_data)
{
for(int n = 0; n < 1000; ++n) {
++cnt;
++acnt;
// for this example, relaxed memory order is sufficient, e.g.
// atomic_fetch_add_explicit(&acnt, 1, memory_order_relaxed);
}
return 0;
}
int main(void)
{
thrd_t thr[10];
for(int n = 0; n < 10; ++n)
thrd_create(&thr[n], f, NULL);
for(int n = 0; n < 10; ++n)
thrd_join(thr[n], NULL);
printf("The atomic counter is %u\n", acnt);
printf("The non-atomic counter is %u\n", cnt);
}
编译并运行:
gcc -std=c11 main.c -pthread
./a.out
可能的输出:
The atomic counter is 10000
The non-atomic counter is 8644
由于跨线程对非原子变量的快速访问,非原子计数器很可能小于原子计数器。
可以在以下位置找到 pthreads 示例:如何在纯 C 中启动线程?
通过从源代码编译 glibc 在 Ubuntu 18.04 (glibc 2.27) 中进行测试:单个主机上的多个 glibc 库Ubuntu 18.10 具有 glibc 2.28,所以应该可以在那里工作。