Causes of difference between thread id in cpp and rust

In the C++ standard library reference, std::thread::id does not uniquely identify each thread created during the lifetime of a process. Once a thread has finished, the value of std::thread::id may be reused by another thread. (not sure if this has been implemented in various standard library implementations.) This is more similar to the Thread Id in the thread_local crate.

In the Rust standard library, ThreadId is obtained by incrementing a static variable and then stored it in a thread local variable, uniquely identifying a thread regardless of whether it has terminated.

What causes this difference?

The different ways they are implemented in Rust and C++. Or do you mean why we decided to provide a uniqueness guarantee while C++ decided not to provide a uniqueness guarantee? My guess would be that Rust decoded to go with the option that is least likely to cause bugs in user code, while C++ decided to go with the fastest option without any regards for how easy it is to misuse the API.

1 Like

You can just this pr as a jumping of point to explore what led to that decision if you like.

4 Likes

Rust uses a custom implementation to uphold its guarantees. I assume C++ wants to retain flexibility for implementations that return the OS thread ID or a number derived from a pointer to a per-thread struct.

1 Like