Hacker News new | ask | show | jobs
by formerly_proven 1482 days ago
Hah, I was thinking about how to share state from an background collector thread to the frontend thread and TripleBuffer is exactly the data structure I needed just now. Thanks!

(My C++-infested instinct was to just go "naw, just slap a mutex on the data, it'll be fiiiinee", but I already knew that Rust Probably Has A Better Way For That).

1 comments

A triple buffer (which isn't even Rust-specific IMO) is a good choice if all you want is polling the latest data at any given time, and you want to avoid mutexes altogether. If you want each piece of data to be delivered exactly once, you can use a queue (bounded or "unlimited" though the latter doesn't supply backpressure which I hear causes problems). SPSC lock-free bounded queues are dead simple to write, and can be better-tuned for higher throughput even with contention. For example, https://github.com/rigtorp/SPSCQueue is C++, claims to be highly optimized, and I haven't had issues working with it (aside from forgetting to peek and pop separately the first time I used it). However it's not a misuse-proof API since it doesn't use the "handles" idea I talked about, so you can push/read/pop from the wrong thread. If you want the reader to poll/WaitForMultipleObjects until the queue has items, that has to be done separately from the SPSC or triple buffer.

And mutexes make a lot of things easier... and introduces "oops wrong mutex!" (Rust solves it) and deadlock (Rust doesn't solve it).