Why multi thread does not return different id

Code

use std::process;
use threadpool::ThreadPool;

fn main() {
    let size = 8;
    let pool: ThreadPool = ThreadPool::new(size);

    (0..size).for_each(|i| {
        pool.execute(move || {
            println!("{} - {}", i, process::id());
        });
    });

    pool.join();
}

Result

0 - 91708
1 - 91708
3 - 91708
2 - 91708
4 - 91708
7 - 91708
6 - 91708
5 - 91708

Unable to get each thread/process id;

Because it's a threadpool - so the number of threads is fixed and will be recycled for different tasks (more accurately, multiple tasks will be scheduled to the same thread).
If you want one thread per task, use std::thread::spawn.

The tasks probably weren't big enough for it to use more than one of the threads in the pool.

1 Like

@RedDocMD @alice Thanks

Here is the thread spawn code with long process but still same result

Code

use std::process;
use std::thread::{spawn, JoinHandle};

fn main() {
    let size = 8;
    let mut p: Vec<JoinHandle<()>> = Vec::new();

    (0..size).for_each(|i| {
        let s = spawn(move || {
            println!("{} - {}", i, process::id());
            loop {}
        });

        p.push(s);
    });

    for pp in p {
        pp.join().unwrap();
    }
}

Result

0 - 93611
1 - 93611
3 - 93611
2 - 93611
4 - 93611
5 - 93611
7 - 93611
6 - 93611

You are querying the process ID, not the thread ID. Use std::thread::current().id().

4 Likes

Thanks @jschievink
But I think this is more index & not actual process id that assign by os.

It looks like Rust has nothing in the standard library for getting the current thread ID. With the JoinHandle returned from thread::spawn(), one can call JoinHandleExt::as_pthread_t() to get the corresponding pthread_t, but the OS thread ID is not exposed. Outside of the standard library, one can call the function nix::unistd::gettid() from the nix crate to get the OS thread ID.

If you want the current thread id, the following should suffice:

std::thread::current().id()

Which does indeed show that different threads are created: Playground.

1 Like

Thread::id() does not return the thread ID as reported by the OS, nor the handle as reported by libpthread, but instead an opaque ID useful only for distinguishing threads. Currently, it's implemented using an incrementing static variable, which is what OP means by an "index".

Ah, fair enough. In that case your answer delving into platform specific solutions makes sense.