Is there a way to get the current process id and thread id in Rust as integers?
The closest I got was ::std::thread::current().id()
which returns an opaque ThreadId
object. When trying to access its u64
field, I'm getting:
error[E0611]: field `0` of tuple-struct `std::thread::ThreadId` is private
--> src\main.rs:4:13
|
4 | let x: u64 = ::std::thread::current().id().0;
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
I couldn't find anything related to the process id in the standard library.
I don't think that ThreadId
even tracks this. The implementation of ThreadId
only has a 64-bit counter that increases with each thread; it does not appear to do anything regarding the underlying threading system.
If you have the JoinHandle
, you can get the ID from the underlying thread system. Once you have that, you can call the appropriate thread system function to get its ID and potentially the OS' ID
On Linux, you can get the pthread_t handle via JoinHandleExt::as_pthread_t
. You can likely get an equivalent on other platforms where pthreads is not available.
Note that
The thread ID returned by
pthread_self()
is not the same thing as the kernel thread ID returned by a call togettid(2)
.
pthread_self
manpage
This was stabilized in Rust 1.26 as process::id
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With