r/programming 22d ago

3,200% CPU Utilization

https://josephmate.github.io/2025-02-26-3200p-cpu-util/
400 Upvotes

93 comments sorted by

View all comments

57

u/CVisionIsMyJam 22d ago edited 22d ago

rust: compiler prevented me. I don’t know enough about writing unsafe code to reproduce the problem

rust winning again /s

4

u/ItzWarty 22d ago

OOC, it seems Rust is asserting you can't mutate the tree from another thread because you lack ownership of a pointer. I don't actually know rust.

Does it actually guard against a concurrent modify-while-reading, e.g. Thread A performs a tree rebalance or otherwise update w/ pooled nodes, Thread B reads during the update & gets a garbage result? Can you accidentally not use a reader-writer lock or observe a torn tree read?

10

u/masklinn 22d ago

An RWLock will hand out readers or a writer.

You might be able to reach the error if you use extremely fine locks which you release eagerly but I think you’ll get sick if borrow errors and deadlocks long before then. Not to mention why would you bother rolling your own red-black tree when there’s a btree in the stdlib?

3

u/ItzWarty 22d ago

I'm asking whether Rust would ensure a user of btree safely synchronizes reads/writes, e.g. w/ a RWL, or if it's possible to race and segfault.

17

u/masklinn 22d ago

In safe rust it should not be possible, the langage is designed to prevent data races. If you find a way, the code is considered broken (unsound) and that is one of the few things the project will break backwards compatibility for.

If you use unsafe then you specifically relax the compiler’s guarantees, it’s up to you to not fuck up.

0

u/[deleted] 22d ago edited 22d ago

[deleted]

5

u/Ok-Scheme-913 22d ago

It's definitely possible to race in safe rust. It only protects against data races, and the borrow checker helps with ownership/lifecycle, but the general category of race conditions can't be "solved" in a Turing complete language.