Skip to content

Commit 1484892

Browse files
committed
rand: enable support of macos
Enhance rand::timestamp_cycles() to support Darwin/macos. Signed-off-by: Liu Jiang <[email protected]>
1 parent c92e124 commit 1484892

File tree

1 file changed

+14
-3
lines changed

1 file changed

+14
-3
lines changed

src/rand.rs

Lines changed: 14 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -24,17 +24,28 @@ pub fn timestamp_cycles() -> u64 {
2424

2525
#[cfg(not(target_arch = "x86_64"))]
2626
{
27+
use std::sync::atomic::{AtomicU64, Ordering};
28+
static TIMESTAMP: AtomicU64 = AtomicU64::new(0);
2729
const MONOTONIC_CLOCK_MULTPIPLIER: u64 = 1_000_000_000;
2830

2931
let mut ts = libc::timespec {
3032
tv_sec: 0,
3133
tv_nsec: 0,
3234
};
3335

34-
unsafe {
35-
libc::clock_gettime(libc::CLOCK_MONOTONIC, &mut ts);
36+
// clock_gettime(libc::CLOCK_MONOTONIC) may return the same value, so retry...
37+
loop {
38+
unsafe { libc::clock_gettime(libc::CLOCK_MONOTONIC, &mut ts) };
39+
let curr = (ts.tv_sec as u64) * MONOTONIC_CLOCK_MULTPIPLIER + (ts.tv_nsec as u64);
40+
let prev = TIMESTAMP.load(Ordering::Acquire);
41+
if prev < curr
42+
&& TIMESTAMP
43+
.compare_exchange(prev, curr, Ordering::AcqRel, Ordering::Relaxed)
44+
.is_ok()
45+
{
46+
return curr;
47+
}
3648
}
37-
(ts.tv_sec as u64) * MONOTONIC_CLOCK_MULTPIPLIER + (ts.tv_nsec as u64)
3849
}
3950
}
4051

0 commit comments

Comments
 (0)