Skip to main content

libdd_common/
threading.rs

1// Copyright 2026-Present Datadog, Inc. https://www.datadoghq.com/
2// SPDX-License-Identifier: Apache-2.0
3
4/// Returns a numeric identifier for the current OS thread.
5#[cfg(target_os = "linux")]
6pub fn get_current_thread_id() -> i64 {
7    // SAFETY: syscall(SYS_gettid) has no preconditions for current thread.
8    unsafe { libc::syscall(libc::SYS_gettid) as i64 }
9}
10
11/// Returns a numeric identifier for the current OS thread.
12#[cfg(target_os = "macos")]
13pub fn get_current_thread_id() -> i64 {
14    let mut tid: u64 = 0;
15    // SAFETY: `pthread_threadid_np` has no preconditions for current thread
16    // when pthread_t is 0 and output pointer is valid.
17    let rc = unsafe { libc::pthread_threadid_np(0, &mut tid) };
18    debug_assert_eq!(
19        rc,
20        0,
21        "pthread_threadid_np failed: {rc} ({})",
22        std::io::Error::from_raw_os_error(rc)
23    );
24    tid as i64
25}
26
27/// Returns a numeric identifier for the current OS thread.
28#[cfg(target_os = "windows")]
29pub fn get_current_thread_id() -> i64 {
30    // SAFETY: GetCurrentThreadId has no preconditions.
31    unsafe { windows_sys::Win32::System::Threading::GetCurrentThreadId() as i64 }
32}
33
34/// Returns a numeric identifier for the current OS thread.
35#[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "windows")))]
36compile_error!("libdd_common::threading::get_current_thread_id is unsupported on this platform");