Question: In an attempt to build an "emulated" [Reentrant mutex](https://en.wikipedia.org/wiki/Reentrant_mutex), I need an identifier that is unique to each thread. I can get the current thread via [`thread::current`](https://doc.rust-lang.org/std/thread/fn.current.html), but [`Thread`](https://doc.rust-lang.org/std/thread/struct.Thread.html) doesn't seem to have anything that could be used (or abused) as an identifier.

For my purposes, I believe the identifier can be reused once a thread exits, although I would be also interested in answers that didn't reuse identifiers as those may be useful in other cases.

Answer: 
Another way is, if you can use `libc`:

```
fn get_thread_id() -> libc::pthread_t {
    unsafe { libc::pthread_self() }
}

```

`pthread_t` will map to the right target per plattform.
Although it would be much nicer to use something built-in to the threading system, one solution is to track our own thread IDs. These can be created using a combination of atomic and thread-local variables:

```
use std::sync::atomic;
use std::thread;

static THREAD_COUNT: atomic::AtomicUsize = atomic::ATOMIC_USIZE_INIT;
thread_local!(static THREAD_ID: usize = THREAD_COUNT.fetch_add(1, atomic::Ordering::SeqCst));

fn thread_id() -> usize {
    THREAD_ID.with(|&id| id)
}

// Example usage

fn main() {
    println!("{}", thread_id());

    let handles: Vec<_> = (0..10).map(|_| { 
        thread::spawn(|| {
            println!("{}", thread_id());
        })
    }).collect();

    for h in handles { h.join().unwrap() }
}

```