1

I have a tree and I want each node of the tree to have a pointer to its parent.

struct DataDeclaration {
    parent: Option<Arc<DataDeclaration>>,
    children: Option<Vec<Weak<DataDeclaration>>>,
    properties: HashMap<Identifier, DataDeclarationProperty>,
}

This creates a cycle, so I use Weak to make sure the memory doesn’t live indefinitely. This tree will be immutable for the entire length of my application except, of course, when the tree is constructed.

In order to create this tree, do I need to use a Mutex or RwLock from the standard library or parking_lot? Will there be a negative performance impact if I only use the lock for reads?

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Calebmer
  • 2,972
  • 6
  • 29
  • 36

1 Answers1

4

do I need to use a Mutex or RwLock

Yes.

There's no practical way to have the type be temporarily mutable while you construct it and then "jettisoning" the ability to be mutated for some period of time (until destruction when it needs to become mutable again)

Will there be a negative performance impact

Yes.

Will the impact be meaningful or important? That depends on a whole host of factors that are not answerable outside of the scope of your entire program and a specific set of usages.

The impact will probably be higher if you use a Mutex instead of a RwLock as a Mutex only allows one thread access at a time. A RwLock will allow multiple concurrent threads.

See also:


Everything here is also true for single-threaded contexts, replacing Arc with Rc and RwLock with RefCell.

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366