Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the current thread id and process id as integers?

Tags:

rust

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.

like image 973
Shmoopy Avatar asked Nov 02 '17 12:11

Shmoopy


1 Answers

Thread id

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 to gettid(2).

pthread_self manpage

Process id

This was stabilized in Rust 1.26 as process::id.

like image 64
Shepmaster Avatar answered Sep 19 '22 02:09

Shepmaster