简单赋值运算符的原子性 [英] Atomicity of the simple assignment operator

查看:93
本文介绍了简单赋值运算符的原子性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

C11标准说,对于原子类型(_Atomic),前缀和后缀++--操作

C11 Standard says that for atomic types (_Atomic), prefix and postfix ++ and -- operations are atomic (6.5.2.4.,p2), as are compound assignments: op= (6.5.16.2,p3).

我还没有发现有关简单作业=的任何内容.它也是原子的吗?

I haven't found anything written about a simple assignment =. Is it also atomic?

让我们说E1,E2是int,但只有E1是用说明符_Atomic定义的. 我的假设是:

Let's says E1, E2 are int, but only E1 is defined with the specifier _Atomic. My assumption is that this:

E1 = E2;

等效于:

atomic_store( &E1 , E2 );

我的假设正确吗?

推荐答案

按照此 C11标准(ISO/IEC 9899:2011)第6.2.6.1/9节内容为:

The C11 standard (ISO/IEC 9899:2011), section 6.2.6.1/9 reads:

具有原子类型的对象的加载和存储通过 memory_order_seq_cst语义.

Loads and stores of objects with atomic types are done with memory_order_seq_cst semantics.

除了是原子操作之外,使用memory_order_seq_cst语义执行的操作还具有所有线程都遵循的单一顺序(即顺序一致的排序).

In addition to being atomic, operations performed with memory_order_seq_cst semantics have a single ordering observed by all threads (aka sequentially-consistent ordering).

如果没有_Atomic类型限定符,则分配可能是非原子的.在32位计算机上分配64位值(例如long long)需要两个CPU周期.如果另一个线程在这两个周期之间读取值,则它们将获得旧值的4个字节和新值的4个字节.

Without the _Atomic type qualifier, it is possible for an assignment to be non-atomic. Assigning a 64 bit value (e.g. a long long) on a 32 bit machine requires two CPU cycles. If another thread reads the value between those two cycles they'll get 4 bytes of the old value and 4 bytes of the new value.

这篇关于简单赋值运算符的原子性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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