Skip to content

How to call Python function in a Tokio request handler #2182

Answered by mejrs
owenthereal asked this question in Questions
Discussion options

You must be logged in to vote

I think it's related to that I block the pyfunction

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

Replies: 3 comments

Comment options

You must be logged in to vote
0 replies
Answer selected by owenthereal
Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
0 replies
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
2 participants