Skip to content

Commit dc11aa5

Browse files
mkuchnikmeta-codesync[bot]
authored andcommitted
Fix MacOS build dependency on gettid (#2154)
Summary: This diff cases out thread ID utilities based on Linux or MacOS. On Linux, we use existing calls. On MacOS, we convert [pthread_threadid_np](https://www.manpagez.com/man/3/pthread_threadid_np/) into the Linux interface. Fixes #2153 Pull Request resolved: #2154 Reviewed By: zdevito Differential Revision: D89375316 Pulled By: mkuchnik fbshipit-source-id: ee1bd7264b7fbd3334580c948ab14f1fc3b823ad
1 parent 225281a commit dc11aa5

File tree

1 file changed

+29
-1
lines changed

1 file changed

+29
-1
lines changed

monarch_hyperactor/src/runtime.rs

Lines changed: 29 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -97,10 +97,38 @@ fn get_main_thread_native_id() -> i64 {
9797
})
9898
}
9999

100+
/// Returns the current thread's native ID in a cross-platform way.
101+
#[cfg(target_os = "linux")]
102+
fn get_current_thread_id() -> i64 {
103+
nix::unistd::gettid().as_raw() as i64
104+
}
105+
106+
/// Returns the current thread's native ID in a cross-platform way.
107+
#[cfg(target_os = "macos")]
108+
fn get_current_thread_id() -> i64 {
109+
let mut tid: u64 = 0;
110+
// pthread_threadid_np with thread=0 (null pthread_t) gets the current thread's ID.
111+
unsafe {
112+
let ret = libc::pthread_threadid_np(0, &mut tid);
113+
debug_assert_eq!(
114+
ret, 0,
115+
"pthread_threadid_np failed with error code: {}",
116+
ret
117+
);
118+
}
119+
// macOS thread IDs are u64 so we need to convert to i64.
120+
debug_assert!(tid <= i64::MAX as u64, "thread ID {} exceeds i64::MAX", tid);
121+
tid as i64
122+
}
123+
124+
/// Returns the current thread's native ID in a cross-platform way.
125+
#[cfg(not(any(target_os = "linux", target_os = "macos")))]
126+
compile_error!("get_current_thread_id is only implemented for Linux and macOS");
127+
100128
/// Returns true if the current thread is the main Python thread.
101129
/// Compares the current thread's native ID against the main Python thread's native ID.
102130
pub fn is_main_thread() -> bool {
103-
let current_tid = nix::unistd::gettid().as_raw() as i64;
131+
let current_tid = get_current_thread_id();
104132
current_tid == get_main_thread_native_id()
105133
}
106134

0 commit comments

Comments
 (0)