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

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

问题描述

给定一个 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天全站免登陆