获取当前线程 id 和进程 id 作为整数? [英] Get the current thread id and process id as integers?
问题描述
有没有办法以整数形式获取 Rust 中的当前进程 ID 和线程 ID?
Is there a way to get the current process id and thread id in Rust as integers?
我得到的最接近的是 ::std::thread::current().id()
,它返回一个不透明的 ThreadId
对象.尝试访问其 u64
字段时,我得到:
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;
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
我在标准库中找不到与进程 ID 相关的任何内容.
I couldn't find anything related to the process id in the standard library.
推荐答案
Thread id
我认为 ThreadId
甚至不会跟踪这个.实现ThreadId
只有一个 64 位计数器,随着每个线程增加;它似乎没有对底层线程系统做任何事情.
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.
如果你有 JoinHandle
,可以从底层线程系统中获取ID.一旦你有了它,你就可以调用适当的线程系统函数来获取它的 ID 和可能操作系统的 ID
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
在 Linux 上,您可以通过 JoinHandleExt::as_pthread_t
.您可能会在 pthreads 不可用的其他平台上获得等价物.
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.
注意
pthread_self()
返回的线程 ID 与调用 gettid(2)
返回的内核线程 ID 不同.
The thread ID returned by
pthread_self()
is not the same thing as the kernel thread ID returned by a call togettid(2)
.
进程 ID
这在 Rust 1.26 中稳定为 process::id
.
这篇关于获取当前线程 id 和进程 id 作为整数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!