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

Time:03-06

I have a struct Node. Inside is a pointer to next Node (Node *next).

My graph is such that every next pointer can only point to one node and the same node that is already present in the graph.

In my example multiple threads can operate on nodes. Consider below example, while knowing that nodes a and b are safely added before to the graph.

Code example:

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

// from now on multiple threads at the same time

a->next = b;

Can a->next be invalid considering that pointer assignment is not atomic?

Edit 1: I am checking next pointers after all threads stop running.

CodePudding user response:

Unsynchronized concurrent writes to the same non-atomic variable cause undefined behavior.

[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.

Your specific scenario sounds like it might work in practice, but I wouldn't do it, unless you already tried atomics and benchmarking shows them to cause performance problems.

If you're going to use atomics, you can try writing to them using std::memory_order_relaxed. From your description, it looks like it would be safe.

CodePudding user response:

If you are checking a->next after all threads have finished the assignment. It will be valid.

  • Related