在以下情况下从多个线程分配指针是否安全?

Is it safe to assign pointer from multiple threads in below situation?

我有一个结构节点。里面是指向下一个节点(Node *next)的指针。

我的图是这样的,每个下一个指针只能指向一个节点和图中已经存在的同一节点。

在我的示例中,多个线程可以在节点上运行。考虑以下示例,同时知道节点 a 和 b 已安全添加到图中。

代码示例:

Node* a = new Node;
Node* b = new Node;

// from now on multiple threads at the same time

a->next = b;

考虑到指针分配不是原子的,a->next 可以无效吗?

编辑 1: 我正在检查所有线程停止后的下一个指针 运行。

如果在所有线程完成分配后检查a->next。它将有效。

对同一 non-atomic 变量的不同步并发写入导致未定义的行为。

[intro.races]/2:

Two expression evaluations conflict if one of them modifies a memory location ([intro.memory]) and the other one reads or modifies the same memory location.

[intro.races]/21

... The execution of a program contains a data race if it contains two potentially concurrent conflicting actions, at least one of which is not atomic, and neither happens before the other ...

Any such data race results in undefined behavior.

你的具体场景听起来可能在实践中可行,但我不会这样做,除非你已经尝试过原子并且基准测试表明它们会导致性能问题。

如果您打算使用原子,您可以尝试使用 std::memory_order_relaxed 写入它们。从你的描述来看,应该是安全的。