C11 atomics 最小可运行示例
通过在 glibc 2.28 中添加线程,我们可以在纯 C11 中进行原子处理和线程处理。
示例来自:https://en.cppreference.com/w/c/language/atomic
main.c
#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 示例:How do I start threads in plain C?
通过从源代码编译 glibc 在 Ubuntu 18.04 (glibc 2.27) 中进行测试:Multiple glibc libraries on a single host Ubuntu 18.10 具有 glibc 2.28,所以应该可以在那里工作。