并发读取非原子变量 [英] Concurrent reads on non-atomic variable

查看:61
本文介绍了并发读取非原子变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在尝试实现共享指针时遇到了这个问题.让我们集中讨论托管数据指针.它的生命周期可以分为三个阶段:

  1. 没有并发访问权限的构造.
  2. 并发读取(无写入).
  3. 没有并发访问权限的销毁.这是通过引用计数来保证的.

我的问题是,鉴于这种情况,指针是否必须是原子的?我认为这等效于:如果指针不是原子的,第二阶段会导致未定义的行为吗?理想情况下,我想听到一个从理论(语言律师)角度和实践角度进行讨论的答案.例如,如果不是原子的,则阶段2在理论上可能是未定义的行为,但在实际平台上实际上是可以的.为了实现共享指针,如果非原子性还可以,则托管指针可以为 unique_ptr< T> ,否则必须为 atomic< T *> .

更新

我找到了标准文字(第1.10 p21节):

如果一个程序的执行包含两个,则该执行包含一个数据争用不同线程中发生冲突的动作,其中至少一个不是原子的,两者都不会发生.任何此类数据竞赛导致未定义的行为.

我猜并发读取不会归类为冲突动作.可以肯定有人找到一些标准的文字吗?

解决方案

由于在中发现的冲突评估的定义,并发读取任何变量(无论是否为原子)都不构成数据争用..multithread] :

如果两个表达式求值中的一个修改了一个内存位置,而另一个表达式访问或修改了相同的内存位置,则这两个表达式求值存在冲突.

最近,它已经转移到 [intro.races] ,其措辞非常微妙

如果两个表达式评估其中一个修改了内存位置,而另一个表达式读取或修改了相同的内存位置,则发生冲突 .

访问 reads 的更改发生在草案n4296和n4431之间.多线程部分的拆分发生在n4582和n4604之间.

I encounter this question while trying to implement a shared pointer. Let's focus on the managed data pointer. Its lifetime can be divided into three stages:

  1. Construction where there is no concurrent access.
  2. Concurrent reads on it (no writes).
  3. Destruction where there is no concurrent access. This is guaranteed by reference counting.

My question is, given this situation, is it necessary for the pointer to be atomic? I think it's equivalent to: will stage 2 lead to undefined behavior if the pointer is not atomic? Ideally, I want to hear an answer discussing from both a theoretical (language-lawyer) point of view and a practical point of view. For example, if not atomic, stage 2 may be undefined behavior theoretically, but is practically OK on actual platforms. For implementing shared pointer, if non-atomic is OK, the managed pointer can be unique_ptr<T>, otherwise it has to be atomic<T*>.

Update

I find the standard text (Section 1.10 p21):

The execution of a program contains a data race if it contains two conflicting actions in different threads, at least one of which is not atomic, and neither happens before the other. Any such data race results in undefined behavior.

I guess concurrent reads do not classify as conflicting actions. Could somebody find some standard text about this to be sure?

解决方案

Concurrent reads on any variable, whether atomic or not, do not constitute a data race, because of the definition of conflicting evaluations, found in [intro.multithread]:

Two expression evaluations conflict if one of them modifies a memory location and the other one accesses or modifies the same memory location.

Recently, this has moved to [intro.races] with a very subtle change in wording

Two expression evaluations conflict if one of them modifies a memory location and the other one reads or modifies the same memory location.

The change from accesses to reads took place between draft n4296 and n4431. The splitting of the multithreading section took place between n4582 and n4604.

这篇关于并发读取非原子变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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