Skip to content

Commit 93d945f

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 93d945f

File tree

1 file changed

+20
-4
lines changed

1 file changed

+20
-4
lines changed

src/rand.rs

Lines changed: 20 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -30,11 +30,27 @@ pub fn timestamp_cycles() -> u64 {
3030
tv_sec: 0,
3131
tv_nsec: 0,
3232
};
33-
34-
unsafe {
35-
libc::clock_gettime(libc::CLOCK_MONOTONIC, &mut ts);
33+
unsafe { libc::clock_gettime(libc::CLOCK_MONOTONIC, &mut ts) };
34+
let mut curr = (ts.tv_sec as u64) * MONOTONIC_CLOCK_MULTPIPLIER + (ts.tv_nsec as u64);
35+
36+
// On macos, clock_gettime(libc::CLOCK_MONOTONIC) may return the same value, so retry...
37+
#[cfg(target_os = "macos")]
38+
loop {
39+
use std::sync::atomic::{AtomicU64, Ordering};
40+
static TIMESTAMP: AtomicU64 = AtomicU64::new(0);
41+
let prev = TIMESTAMP.load(Ordering::Acquire);
42+
if prev < curr
43+
&& TIMESTAMP
44+
.compare_exchange(prev, curr, Ordering::AcqRel, Ordering::Relaxed)
45+
.is_ok()
46+
{
47+
break;
48+
}
49+
unsafe { libc::clock_gettime(libc::CLOCK_MONOTONIC, &mut ts) };
50+
curr = (ts.tv_sec as u64) * MONOTONIC_CLOCK_MULTPIPLIER + (ts.tv_nsec as u64);
3651
}
37-
(ts.tv_sec as u64) * MONOTONIC_CLOCK_MULTPIPLIER + (ts.tv_nsec as u64)
52+
53+
return curr;
3854
}
3955
}
4056

0 commit comments

Comments
 (0)