rust-random / getrandom

A small cross-platform library for retrieving random data from (operating) system source
Apache License 2.0
264 stars 166 forks source link

Android/Linux/rdrand: Use once_cell::race::OnceBool instead of LazyBool. #483

Open briansmith opened 2 weeks ago

briansmith commented 2 weeks ago

Remove src/lazy.rs.

lazy::LazyBool had "last to win the race" semantics. When multiple threads see an uninitialized LazyBool, all of them will calculate a value. As they finish, each one will overwrite the value set by the thread that finished previously. If two threads calculate different values for the boolean, then the value of the boolean can change during the period where the threads are racing. This doesn't seem to be a huge issue with the way it is currently used, but it is hard to reason about.

once_cell::race::OnceBool has "first to win the race" semantics. When multiple threads see an uninitialized OnceBool, all of them will calculate a value. The first one to finish will write its value; the rest will have their work ignored. Thus there is never any change in the stored value at any point. This is much easier to reason about.

The different semantics come down to the fact that once_cell uses AtomicUsize::compare_exchange whereas lazy.rs was using AtomicUsize::store.

newpavlov commented 2 weeks ago

I don't think that adding a new dependency to save less than 10 lines of straightforward code is worthwhile.

briansmith commented 2 weeks ago

I don't think that adding a new dependency to save less than 10 lines of straightforward code is worthwhile.

This is designed to accompany #481, which adds a more important once_cell dependency.

briansmith commented 2 weeks ago

I updated the commit message (and the GitHub issue description) to emphasize the difference in semantics, before and after.