How to share reference to a DB pool

Hello I'm using the bb8 package to create a Redis and Postgres pool. My issue is I don't understand how to effectively share the pool.

My current implementation uses Arc and passes down through the entire chain of functions to get where I need to use it, but that seems to have a lot of overhead for sharing something that isn't really changing.

The Pool object is internally reference counted. Just call .clone() directly on the Pool.

Thanks. One more similar question.

I have a map of TCP connections that I need to be able to share among all threads. What I am imagining is a unsafe global map accessed with a mutex. I'm sure there's a safe way to do that, could you advise how?

RwLock<HashMap<K, Mutex<V>>> perhaps?

Aren't global variables that aren't static always unsafe?

The RwLock satisfies that, because immutable refs to locks turn into mutable refs for the value once you lock them (for writing in this case).

Some things need complex initialization, use lazy_static for that.

That's great! thanks.

As a word of advice, putting io resources in a Mutex almost always turns out to be a poor design. Typically it is better to spawn a task for each io resource, giving that task exclusive ownership of it, then "sharing" it by talking to the task.

See more on this here.

1 Like