我对获取在Rust程序中创建的线程的PID感兴趣。如documentation中所述,thread::id()不适用于此目的。我发现Get the current thread id and process id as integers?似乎是答案,但我的实验表明它不起作用。

这是代码:

extern crate rand;
extern crate libc;

use std::thread::{self, Builder};
use std::process::{self, Command};
use rand::thread_rng;
use rand::RngCore;
use std::time::Duration;
use std::os::unix::thread::JoinHandleExt;
use libc::pthread_t;

fn main() {
    let main_pid = process::id();
    println!("This PID {}", main_pid);

    let b = Builder::new().name(String::from("LongRunningThread")).spawn(move || {
        let mut rng = thread_rng();
        let spawned_pid = process::id();
        println!("Spawned PID {}", spawned_pid);
        loop {
            let u = rng.next_u64() % 1000;
            println!("Processing request {}", u);
            thread::sleep(Duration::from_millis(u));
        }

    }).expect("Could not spawn worker thread");

    let p_threadid : pthread_t = b.as_pthread_t();
    println!("Spawned p_threadid {}", p_threadid);
    let thread_id = b.thread().id();
    println!("Spawned thread_id {:?}", thread_id);

    thread::sleep(Duration::from_millis(60_000));
}

在Linux机器内运行程序的输出如下:

This PID 8597
Spawned p_threadid 139858455706368. <-- Clearly wrong
Spawned thread_id ThreadId(1) <-- Clearly wrong
Spawned PID 8597
Processing request 289
Processing request 476
Processing request 361
Processing request 567

以下是我系统中htop输出的摘录:

 6164  1026 root       20   0   98M  7512  6512 S  0.0  0.0  0:00.03 │  ├─ sshd: dash [priv]
 6195  6164 dash       20   0   98M  4176  3176 S  0.0  0.0  0:00.20 │  │  └─ sshd: dash@pts/11
 6196  6195 dash       20   0 22964  5648  3408 S  0.0  0.0  0:00.09 │  │     └─ -bash
 8597  6196 dash       20   0  2544     4     0 S  0.0  0.0  0:00.00 │  │        └─ ./process_priorities
 8598  6196 dash       20   0  2544     4     0 S  0.0  0.0  0:00.00 │  │           └─ LongRunningThre

我想要的派生线程的PID是8598,但是我不知道如何在Rust程序中获取它。有任何想法吗?

最佳答案

我使用一个名为Palaver的现有 crate 找到了答案。它包含一个跨平台工作的gettid()。唯一需要注意的是, crate 的默认配置使用夜间功能,因此,如果您处于稳定状态,请确保像palaver = { version = "*", default-features = false }这样禁用它们

现在,当我运行使用gettid()的代码时,这是输出:

This PID 9009
Priority changed for thread
Spawned PID 9010
Processing request 803
Processing request 279
Processing request 624

和我的htop的输出:

 6164  1026 root       20   0   98M  7512  6512 S  0.0  0.0  0:00.03 │  ├─ sshd: dash [priv]
 6195  6164 dash       20   0   98M  4176  3176 S  0.0  0.0  0:00.21 │  │  └─ sshd: dash@pts/11
 6196  6195 dash       20   0 22964  5648  3408 S  0.0  0.0  0:00.10 │  │     └─ -bash
 9009  6196 dash       20   0  2544     4     0 S  0.0  0.0  0:00.00 │  │        └─ ./process_priorities
 9010  6196 dash       20   0  2544     4     0 S  0.0  0.0  0:00.00 │  │           └─ LongRunningThre

09-20 04:32