如何在C中使用原子变量? [英] How to use atomic variables in C?
问题描述
我需要在C语言中使用一个原子变量,因为跨不同线程访问此变量.不想比赛条件.
I need to use an atomic variable in C as this variable is accessed across different threads. Don't want a race condition.
我的代码在CentOS上运行.我有什么选择?
My code is running on CentOS. What are my options?
推荐答案
If you are using GCC on your CentOS platform, then you can use the __atomic
built-in functions.
此功能可能特别令人感兴趣:
Of particular interest might be this function:
—内置功能:
bool __atomic_always_lock_free (size_t size, void *ptr)
如果size
字节的对象始终为目标体系结构生成无锁原子指令,则此内置函数返回true.size
必须解析为编译时常量,结果也解析为编译时常量.
ptr
是指向对象的可选指针,可用于确定对齐方式.值0
表示应使用典型的对齐方式.编译器也可能会忽略此参数.
— Built-in Function:
bool __atomic_always_lock_free (size_t size, void *ptr)
This built-in function returns true if objects ofsize
bytes always generate lock free atomic instructions for the target architecture.size
must resolve to a compile-time constant and the result also resolves to a compile-time constant.
ptr
is an optional pointer to the object that may be used to determine alignment. A value of0
indicates typical alignment should be used. The compiler may also ignore this parameter.
if (_atomic_always_lock_free (sizeof (long long), 0))
这篇关于如何在C中使用原子变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!