How are we supposed to run coroutines?

As the entry point (the main function) cannot be async, is there any way to call a coroutine from a syncron context? Here just an easy example code what I'm testing and trying to do:
async fn test():
print("test")

fn main():
await test()
async fn test():
print("test")

fn main():
await test()
6 Replies
Melody Daniel
Melody Daniel16mo ago
There should be some sort of event loop runtime, I can't find any on the docs though. For example in Python you can synchronously use the asyncio runtime like so - asyncio.run(coro, *, debug=None) - Perhaps Mojo doesn't ship with a runtime at the moment.
Alex Kirchhoff
Alex Kirchhoff16mo ago
There is no code in Mojo that pumps an event loop at the moment, but you could write one yourself if you wanted. Take a look at the coroutine module: https://docs.modular.com/mojo/stdlib/builtin/coroutine.html. In particular, you can kick off a coroutine synchronously using Coroutine.__call__:
async fn my_async_fn() -> Int:
print("I am asynchronous")
return 5

fn main():
print("About to call my_async_fn")
let coro = my_async_fn()
print("About to resume coroutine")
let value = coro()
print("Returned from coroutine")
print("Coroutine result =", value)
async fn my_async_fn() -> Int:
print("I am asynchronous")
return 5

fn main():
print("About to call my_async_fn")
let coro = my_async_fn()
print("About to resume coroutine")
let value = coro()
print("Returned from coroutine")
print("Coroutine result =", value)
KingMigDOR [🌐] @ FancyWorld
hopefully mojo would not do the same loop thing as python did, because it's an overcomplicated system for nothing and always pain to do smth like this So basically my_async_fn()() would call a coroutine synchronously? I don't think that's good practise but yeah, at least something
ModularBot
ModularBot16mo ago
Congrats @KingMigDOR [🌐] @ FancyWorld, you just advanced to level 1!
Alex Kirchhoff
Alex Kirchhoff16mo ago
I wouldn't recommend writing that in user code, but if someone were to try to write an async framework (like Python's asyncio), they would need some way to resume the coroutine. For Mojo, that's through calling the coroutine. Essentially, we have language and compiler support for async, but there is not much in terms of a runtime for it right now. The ingredients for a runtime are there, though, if someone wanted to write one.
Melody Daniel
Melody Daniel16mo ago
I don't see how it's overcomplicated, Mojo would still need to have a runtime and a way to start it somehow. Well perhaps the main function can get a decorator
Want results from more Discord servers?
Add your server