`HandleInner` memory address as Tokio Runtime unique identifier

We are trying to define a session variable per #[tokio::test] for the purposes of referencing a per-runtime channel within a global lazy static map through which otherwise independent tasks (or services) can communicate.

Since this channel is only used for testing purposes, we do not want to propogate session variables by proper means.

For this purpose, we determined it is sufficient to discover a runtime-unique number, since #[tokio::test] uses a fresh runtime per test.

Since the HandleInner struct is created exactly once per runtime, is its memory address a suitable candidate for our session variable?

Note that one concern, of course, is that a memory address is not guaranteed to be stable. However, since our use case is testing, not production, we may be ok with this working only 99.99% of the time.

If you're not customizing the behavior of the test runtime I believe it's single threaded, and I believe every Rust function is run in a new thread. So you could probably just use the ThreadId of the current thread.

1 Like

I prefer just declare a static AtomicU64, then use fetch_add(1, Relaxed) to get a unique number.

And then use tokio::task_local to get the unique Id.

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.