C ++ 11内存模型并访问不同线程中相同struct的不同成员 [英] C++11 memory model and accessing different members of the same struct in different threads

查看:297
本文介绍了C ++ 11内存模型并访问不同线程中相同struct的不同成员的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设您有以下定义:

struct X
{
  char a, b;
};

X x;

现在假设你有两个线程,其中一个读写 xa c>,但从不访问 xb ,而另一个读取并写入 xb c $ c> xa 。两个线程都不使用任何锁或其他同步原语。这是否保证在C ++ 11中工作?

And now assume you have two threads, one of which reads and writes x.a but never accesses x.b while the other one reads and writes x.b but never accesses x.a. Neither thread uses any locks or other synchronization primitives. Is this guaranteed to work in C++11? Or does it count as accessing the same object, and therefore need a lock?

推荐答案

这是安全的。引用C ++ 11:

It's safe. Quoting C++11:

[intro.memory] ​​p3:

[intro.memory]p3:


内存位置是标量类型的对象,或是所有具有非零宽度的相邻位域的最大序列。 [注意:语言的各种功能(例如引用和虚拟函数)可能涉及额外的内存位置,这些内存位置对程序不可访问,但由实施管理。 -end note ]两个执行线程(1.10)可以更新和访问单独的内存位置,而不会彼此干扰。

A memory location is either an object of scalar type or a maximal sequence of adjacent bit-fields all having non-zero width. [ Note: Various features of the language, such as references and virtual functions, might involve additional memory locations that are not accessible to programs but are managed by the implementation. —end note ] Two threads of execution (1.10) can update and access separate memory locations without interfering with each other.

[intro.memory] ​​p5:

[intro.memory]p5:


[示例: >



struct {
  char a;
  int b:5,
  c:11,
  :0,
  d:8;
  struct {int ee:8;} e;
}




包含四个单独的内存位置: code> a 和位字段 d e.ee 单独的存储器位置,并且可以同时修改而不彼此干扰。位字段 b c 共同构成第四存储器位置。位字段 b c 不能同时修改,但 b a ,例如,可以。 -end example ]

contains four separate memory locations: The field a and bit-fields d and e.ee are each separate memory locations, and can be modified concurrently without interfering with each other. The bit-fields b and c together constitute the fourth memory location. The bit-fields b and c cannot be concurrently modified, but b and a, for example, can be. —end example ]

这些一起意味着成员 a X b 是单独的内存位置,因此可以同时访问。

These together mean that the members a and b of X are separate memory locations, and can thus be accessed concurrently.

这篇关于C ++ 11内存模型并访问不同线程中相同struct的不同成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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