Is there a bug in the LazyLock function?


I'm not quite sure if this is a problem with LazyLock.
When I was testing the database connection, this connection proved to be valid.
At that time, when I used [DB_CONNECTION.deref()] as a global variable, the database kept timing out during the connection.

what database crate are you using? is the connection tied to the runtime on which it was created? I think the runtime is destroyed after the spawned thread terminated. maybe that's the problem.

Thank you very much. I think what you said is very reasonable.

The future given to block_on is running only when block_on is blocking. When block_on returns, the async code stops.

You get a timeout, because if block_on isn't running, then the async code isn't running. Async runtimes aren't global, and don't exist in the background automatically.

You shouldn't hack sync<>async integration like that. Don't create async runtimes hidden in random places.

If you're using async runtime in your application at all, then create one in fn main() and use async functions.

If you still must run async things when initialising a global variable, then keep the thread with the runtime running forever (never join it), and use mpsc channels to communicate with that thread.

1 Like