如何在C中使用原子变量? [英] How to use atomic variables in C?

查看:1132
本文介绍了如何在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?

推荐答案

如果您在CentOS平台上使用GCC,则可以使用

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 of size 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 of 0 indicates typical alignment should be used. The compiler may also ignore this parameter.

      if (_atomic_always_lock_free (sizeof (long long), 0))

这篇关于如何在C中使用原子变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆