指派对C11原子意味着什么? [英] What does assignment mean to a C11 atomic?

查看:99
本文介绍了指派对C11原子意味着什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,

atomic_int test(void)
{
  atomic_int tmp = ATOMIC_VAR_INIT(14);
  tmp = 47;                    // Looks like atomic_store
  atomic_int mc;               // Probably just uninitialised data
  memcpy(&mc,&tmp,sizeof(mc)); // Probably equivalent to a copy
  tmp = mc + 4;                // Arithmetic
  return tmp;                  // A copy - perhaps load then store
}

Clang对这一切感到满意.我已经阅读了该标准的7.17节,其中谈到了很多有关内存模型和定义的函数(初始化,存储,加载等)的内容,但没有涉及常规操作(+,=等).

Clang is happy with all this. I've read section 7.17 of the standard, and it says a lot about the memory model and the defined functions (init, store, load etc) but doesn't say anything about the usual operations (+, = etc).

另外有趣的是将struct wot { atomic_int value; }传递给函数的行为.

Also of interest is the behaviour of passing struct wot { atomic_int value; } to functions.

我想相信赋值的行为与原子负载相同,然后使用memory_order_seq_cst进行存储.

I would like to believe that assignment behaves identically to an atomic load then store using memory_order_seq_cst.

更乐观的是,我想相信结构赋值,传递给函数,从函数返回甚至memcpy的行为也与仔细复制memory_order_seq_cst下的位模式相同.

Even more optimistically, I would like to believe that struct assignment, passing to function, returning from function and even memcpy also behaves identically to carefully copying the bit pattern across under memory_order_seq_cst.

尽管我找不到任何支持标准的证据.绝对有可能原子原语的赋值和记忆是不确定的行为.

I can't find any supporting evidence for either belief in the standard though. There's definitely a chance that assignment and memcpy of atomic primitives is undefined behaviour.

对原子基元的基元操作应如何表现?

How should primitive operations on atomic primitives behave?

谢谢!

推荐答案

保证对符合_Atomic的对象(和atomic_int只是不同的写法)进行的操作具有顺序一致性.您会发现在语义部分末尾提到的每个操作数. (也许缺少分配的提及.)

Operations on objects that are _Atomic qualified (and atomic_int is just a different writing for that) are guaranteed to have sequential consistency. You find that mentionned at the end of the semantics section for each of the operands. (And maybe the mention for assignment is missing.)

您的代码在两个地方都不正确:初始化必须使用ATOMIC_VAR_INIT宏(7.17.2.1),并且memcpy是未定义的(大小可能不一致),尽管它可能在大多数体系结构上都适用

Your code is not correct at two places: initialization must use the ATOMIC_VAR_INIT macro (7.17.2.1), and memcpy is undefined (the sizes might not agree), although it probably will work on most of the architectures.

还行

tmp = mc + 4;                // Arithmetic

不执行您的评论所声称的.这不是对原子对象的算术运算,而是一个负载和一个普通的加法运算.更有趣的是

doesn't do what your comment claims. This is not arithmetic on an atomic object, but a load followed by an ordinary addition. More interesting would be

mc += 4;                // Arithmetic

这是具有顺序一致性的原子操作.

which is an atomic operation with sequential consistency.

这篇关于指派对C11原子意味着什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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