对原子结构和指针的误解

对原子结构和指针的误解

本文介绍了对原子结构和指针的误解的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的第一个问题是:有什么方法可以访问atomic<struct>对象中的struct成员?例如,我得到编译器错误:

My first question is: Is there any way to access the members of struct in an atomic<struct> object?For example, I get the compiler error:

struct std::atomic<node>’ has no member named ‘data’ a.data = 0;

在此段

struct node{
  int data;
  node* next;
};

int main(){
  atomic<node> a;
  a.data = 0;
}

我可以通过创建一个临时节点来解决它,

I can work around it by creating a temporary node like so:

  atomic<node> a;
  node temp;
  temp.data = 0;
  a.store(temp);

但这似乎不是很优雅.

第二个问题是,如果我有一个指向原子对象的指针怎么办?无论如何,可以直接访问该节点的成员吗?显然,以下内容无法编译,如何更改以将0存储在b节点的值中?

The second question is, what if I have a pointer to an atomic object? Is there anyway to access the members of the node directly? Obviously the following does not compile, how would I change this to store 0 in the value of the node at b?

atomic<node> b = new node;
b->data = 0;

这是我找到的解决方案,但是再次,有没有更优雅的方法呢?

This is a solution I've found, but again, is there a more elegant way of doing this??

atomic<node> *b;
node temp;
temp.data = 0;
b->store(&temp);

最后,atomic<node*>atomic<node>*

推荐答案

std::atomic<T>不能使任意操作原子化:仅支持加载和存储数据.这就是为什么您的解决方法"实际上是处理原子对象的方式:您以自己喜欢的任何方式准备新的node值,然后将其自动设置为atomic<node>变量.

std::atomic<T> cannot make arbitrary operations atomic: only loading and storing the data is supported. That is why your "workaround" is actually the way to deal with atomic objects: you prepare the new node value in any way that you like, and then atomically set it into an atomic<node> variable.

通过指针访问节点的内容也不是原子的:由于std::atomic<T>可以保证仅加载和存储其值是原子的,因此它不允许您访问T的成员而无需显式副本.这是一件好事,因为它可以防止代码的读者误以为对T内部的访问是原子的.

Accessing the content of a node through a pointer would not be atomic as well: since std::atomic<T> can guarantee only loading and storing its value to be atomic, it does not let you access T's members without making an explicit copy. This is a good thing, because it prevents readers of the code from getting a false impression that the access to T's internals is somehow atomic.

在第一种情况下,原子对象存储一个指针,该指针可以被原子访问(即,您可以将该指针原子地指向新节点).在第二种情况下,原子对象存储可以原子访问的值,这意味着您可以原子地读取和写入整个node.

In the firs case, the atomic object stores a pointer, which can be accessed atomically (i.e. you can re-point this pointer to a new node atomically). In the second case, the atomic object stores the value that can be accessed atomically, meaning that you can read and write the entire node atomically.

这篇关于对原子结构和指针的误解的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-22 14:50