Shared mutable state, used in sync and async functions

Hi everyone,

I have some shared state (something that map a new unique id to a given id), ids are u32.
I need to set and get ids from async functions.
I need to get ids from sync function.

I need both sync and async cause sync function are defined in a trait but the implementor is
used in an async context.

Both sync and async mutex are not a solution. Sync mutex cause I do not want to block the thread for obvious reasons. Async mutex cause are not usable from sync function, busy looping on try_lock() is the same of blocking the thread as there is not awaits that can give back control to the runtime.

Most obvious solution would be to make everything async changing the trait in a trait that use async functions instead of sync ones. But I would like to avoid it if possible cause the trait is defined in a separate crate and I would like to have a trait that play nice with sync contexts as well.

What I come up with is something like that:

My questions are:
Does the above code make any sense (eg: I missed something obvious and there are simpler way to achieve the same result, it has race condition, ecc ecc)

How performance-wise it compare with just doing everything async (so no threads to manage the state and no channels, just async mutex and async functions)


Have you seen this Tokio doc on using mutexes? They recommend using a normal (sync) mutex if you are simply protecting a data structure. That would work for both sync and async modes.


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.