rust-cpython icon indicating copy to clipboard operation
rust-cpython copied to clipboard

awaitable example

Open jamesstidard opened this issue 8 years ago • 5 comments
trafficstars

I was looking at writing a rust extension and was wondering how I'd go about making the rust call awaitable from the asyncio async/await. Is that something that is supported at the moment?

jamesstidard avatar Mar 08 '17 14:03 jamesstidard

I doubt it'd be possible without at least heavy use of marcos.

Issue with async is that the event loop needs to regain control each time you do an await, so you can't just have your Rust function work like a regular one, because you can't do the stack jumping nonsense.

Then again I've not really looked into if async C functions with the regular C API are possible (though my quick googles didn't turn up with anything), so hey maybe it is possible.

PJB3005 avatar Mar 08 '17 17:03 PJB3005

technically awaitable object is just iterator. specifically for asyncio, iterator should return asyncio.Future object or result.

I am working on asyncio event loop based on tokio framework https://github.com/fafhrd91/async-tokio network does not work yet, but I have timers, Future and Task objects some tests https://github.com/fafhrd91/async-tokio/blob/master/tests/test_basic.py

fafhrd91 avatar Mar 25 '17 08:03 fafhrd91

Thanks for the response @fafhrd91. I did go ahead and clone your repo, though I wasn't able to get it to run. Though one of the things I had to fiddle with was Cargo's path to the CPython dependency (I assume you've done some tweaks locally which aren't on the main repo yet which is preventing it from running locally for me).

My understanding is that if you wanted to do an awaitable you'd need to also release the GIL in your rust code. Am I right about that?

jamesstidard avatar Mar 25 '17 12:03 jamesstidard

oh, forgot to update deps. my repo should be fixed now. you need #98 pr.

from c-level perspective awaitable is just iterator that return something "awaitable", in case of asyncio you return Future object. so yes, lets say you spawn new thread with computation intensive work, and return Future back to python code, then when result is ready you set it to future. python code can do await your_rust_obj()

fafhrd91 avatar Mar 25 '17 15:03 fafhrd91

@fafhrd91 Oh great, thank you. I've just pulled the latest and will take a look.

jamesstidard avatar Mar 27 '17 19:03 jamesstidard