当另一个线程修改同一数组的另一个元素时,修改数组的一个元素是定义明确的行为吗? [英] Is it well-defined behavior to modify one element of an array while another thread modifies another element of the same array?

查看:66
本文介绍了当另一个线程修改同一数组的另一个元素时,修改数组的一个元素是定义明确的行为吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定一个 foo_t[n] 类型的数组和一组 n 个线程,其中每个 n 个线程读取和修改一个数组的不同元素,我是否需要显式同步数组的修改,还是可以假设同时修改数组的成员是明确定义的行为?foo_t 有多大/它有什么对齐方式有关系吗?

Given an array of type foo_t[n] and a set of n threads, where each of the n threads reads and modifies a different element of the array, do I need to explicitly synchronize modifications of the array or can I assume that concurrently modifying members of the array is well-defined behavior? Does it matter how large foo_t is / what alignment it has?

推荐答案

我尝试做的是明确定义的行为.

What I try to do is well-defined behavior.

参见 ISO/IEC 9899:2011 §5.1.2.4.27:

See ISO/IEC 9899:2011 §5.1.2.4.27:

注意 13 编译器转换将分配引入到抽象机不会修改的潜在共享内存位置,因此该标准通常排除这种分配,因为在以下情况下,此类分配可能会覆盖不同线程的另一个分配抽象机器执行不会遇到数据竞争.这包括数据成员分配的实现,覆盖不同内存位置中的相邻成员.在所讨论的原子可能会出现别名的情况下,我们通常还会排除对原子负载的重新排序,因为这可能违反可见序列"规则.

NOTE 13 Compiler transformations that introduce assignments to a potentially shared memory location that would not be modified by the abstract machine are generally precluded by this standard, since such an assignment might overwrite another assignment by a different thread in cases in which an abstract machine execution would not have encountered a data race. This includes implementations of data member assignment that overwrite adjacent members in separate memory locations. We also generally preclude reordering of atomic loads in cases in which the atomics in question may alias, since this may violate the "visible sequence" rules.

请注意,此语言是在 C11 中引入的,目的是进行优化,从而导致错误像这样非法.C11 之前的编译器可能不遵守此规则.

Note that this language was introduced with C11 to make optimizations that cause bugs like this illegal. Pre-C11 compilers may not abide to this rule.

这篇关于当另一个线程修改同一数组的另一个元素时,修改数组的一个元素是定义明确的行为吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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