Skip to main content

pyo3/platform/
thread.rs

1use core::ffi::c_ulong;
2use core::num::NonZero;
3
4#[cfg(not(wip_feature_std))]
5use pyo3_ffi::PyThread_get_thread_ident;
6
7#[must_use]
8pub fn current() -> Thread {
9    cfg_select! {
10        wip_feature_std => Thread { id: ThreadId(std::thread::current().id()) },
11        _ => Thread {
12            // SAFETY: PyThread_get_thread_ident never returns zero
13            // https://docs.python.org/3/c-api/threads.html#c.PyThread_get_thread_ident
14            id: ThreadId(unsafe { NonZero::new_unchecked(PyThread_get_thread_ident()) }),
15        }
16    }
17}
18
19pub struct Thread {
20    id: ThreadId,
21}
22
23impl Thread {
24    pub fn id(&self) -> ThreadId {
25        self.id
26    }
27}
28
29// This needs to be in a separate mod so that the `expect` attribute covers the derived code.
30#[cfg(wip_feature_std)]
31#[expect(clippy::disallowed_types)]
32mod std_feature {
33    #[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)]
34    pub struct ThreadId(pub(super) std::thread::ThreadId);
35}
36
37#[cfg(wip_feature_std)]
38pub use std_feature::ThreadId;
39
40#[cfg(not(wip_feature_std))]
41#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)]
42pub struct ThreadId(NonZero<c_ulong>);
⚠️ Internal Docs ⚠️ Not Public API 👉 Official Docs Here