Skip to content

Commit 9e0d7c7

Browse files
josephlrnewpavlov
authored andcommitted
Incorperate feedback on Lazy helpers (#60)
1 parent 65660e0 commit 9e0d7c7

File tree

2 files changed

+15
-3
lines changed

2 files changed

+15
-3
lines changed

src/util.rs

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -53,7 +53,8 @@ impl LazyUsize {
5353

5454
// Synchronously runs the init() function. Only one caller will have their
5555
// init() function running at a time, and exactly one successful call will
56-
// be run. The init() function should never return LazyUsize::ACTIVE.
56+
// be run. init() returning UNINIT or ACTIVE will be considered a failure,
57+
// and future calls to sync_init will rerun their init() function.
5758
pub fn sync_init(&self, init: impl FnOnce() -> usize, mut wait: impl FnMut()) -> usize {
5859
// Common and fast path with no contention. Don't wast time on CAS.
5960
match self.0.load(Relaxed) {
@@ -65,7 +66,13 @@ impl LazyUsize {
6566
match self.0.compare_and_swap(Self::UNINIT, Self::ACTIVE, Relaxed) {
6667
Self::UNINIT => {
6768
let val = init();
68-
self.0.store(val, Relaxed);
69+
self.0.store(
70+
match val {
71+
Self::UNINIT | Self::ACTIVE => Self::UNINIT,
72+
val => val,
73+
},
74+
Relaxed,
75+
);
6976
return val;
7077
}
7178
Self::ACTIVE => wait(),

src/util_libc.rs

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -80,7 +80,12 @@ impl LazyFd {
8080
None => LazyUsize::UNINIT,
8181
},
8282
|| unsafe {
83-
libc::usleep(1000);
83+
// We are usually waiting on an open(2) syscall to complete,
84+
// which typically takes < 10us if the file is a device.
85+
// However, we might end up waiting much longer if the entropy
86+
// pool isn't initialized, but even in that case, this loop will
87+
// consume a negligible amount of CPU on most platforms.
88+
libc::usleep(10);
8489
},
8590
);
8691
match fd {

0 commit comments

Comments
 (0)