How to call Python function in a Tokio request handler #2182
-
👋 I'm exploring I would like that:
However, I found that the Another issue is that after the Tonic server starts, pressing I'm fairly new to Pyo3 and I may need some hand-holding 😄 . It would be perfect if you have some example codes that I could take a look at for similar use cases. Thank you in advance! |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments
-
Yes, the tokio runtime is multithreaded, and you have this function hold the GIL the entire time, so any other thread will deadlock when they need to acquire it. So you should probably release it before starting the runtime: #[pyfunction]
fn start_function(py: Python, f: Py<PyFunction>) -> PyResult<()> {
let addr = "127.0.0.1:50051".parse().unwrap();
let func = Function {
callback: Arc::new(f),
};
// 👇 may need `move` here
py.allow_threads(||{
let rt = tokio::runtime::Runtime::new().unwrap();
let serve = Server::builder()
.add_service(function_server::FunctionServer::new(func))
.serve(addr);
rt.block_on(serve).unwrap();
});
Ok(())
} Also, the |
Beta Was this translation helpful? Give feedback.
-
Thanks for the reply! Yes, adding
I'm still having trouble sending sigterm to the running server with |
Beta Was this translation helpful? Give feedback.
-
You'll probably want to look at https://tokio.rs/tokio/topics/shutdown for that. There is also |
Beta Was this translation helpful? Give feedback.
Yes, the tokio runtime is multithreaded, and you have this function hold the GIL the entire time, so any other thread will deadlock when they need to acquire it. So you should probably release it before starting the runtime: