Skip to content

Commit 8f33536

Browse files
committed
Cache tid in futex tls
1 parent a360d54 commit 8f33536

File tree

1 file changed

+30
-6
lines changed

1 file changed

+30
-6
lines changed

library/std/src/sys/pal/unix/pi_futex.rs

+30-6
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,14 @@
11
#[cfg(any(target_os = "linux", target_os = "android"))]
22
mod linux {
3+
use crate::cell::Cell;
34
use crate::ops::Deref;
45
use crate::sync::atomic::AtomicU32;
56
use crate::sys::cvt;
6-
use crate::{io, ptr};
7+
use crate::{io, ptr, thread_local};
8+
9+
thread_local! {
10+
static TID: Cell<u32> = Cell::new(0);
11+
}
712

813
pub type State = u32;
914

@@ -27,7 +32,14 @@ mod linux {
2732
}
2833

2934
pub fn locked() -> State {
30-
(unsafe { libc::gettid() }) as _
35+
let tid = TID.get();
36+
if tid == 0 {
37+
let tid = (unsafe { libc::gettid() }) as u32;
38+
TID.set(tid);
39+
tid
40+
} else {
41+
tid
42+
}
3143
}
3244

3345
pub fn is_contended(futex_val: State) -> bool {
@@ -75,11 +87,16 @@ pub use linux::*;
7587

7688
#[cfg(target_os = "freebsd")]
7789
mod freebsd {
90+
use crate::cell::Cell;
7891
use crate::mem::transmute;
7992
use crate::ops::Deref;
8093
use crate::sync::atomic::AtomicU32;
8194
use crate::sys::cvt;
82-
use crate::{io, ptr};
95+
use crate::{io, ptr, thread_local};
96+
97+
thread_local! {
98+
static TID: Cell<u32> = Cell::new(0);
99+
}
83100

84101
pub type State = u32;
85102

@@ -125,9 +142,16 @@ mod freebsd {
125142
}
126143

127144
pub fn locked() -> State {
128-
let mut tid: libc::c_long = 0;
129-
let _ = unsafe { libc::thr_self(ptr::from_mut(&mut tid)) };
130-
tid as _
145+
let tid = TID.get();
146+
if tid == 0 {
147+
let mut tid: libc::c_long = 0;
148+
let _ = unsafe { libc::thr_self(ptr::from_mut(&mut tid)) };
149+
let tid = tid as u32;
150+
TID.set(tid);
151+
tid
152+
} else {
153+
tid
154+
}
131155
}
132156

133157
pub fn is_contended(futex_val: State) -> bool {

0 commit comments

Comments
 (0)