M
Modular11mo ago
a2svior

Are coroutines executed in parallel?

I'm trying this example:
fn main():
async fn my_async_fn() -> Int:
sleep(2)
return 5

fn my_sync_fn():
let my_coro: Coroutine[Int] = my_async_fn()
print(my_coro())

fn call_em_together():
_ = my_sync_fn()
_ = my_sync_fn()

fn call_em_coroutine():
let my_coro_1: Coroutine[Int] = my_async_fn()
print(my_coro_1())
let my_coro_2: Coroutine[Int] = my_async_fn()
print(my_coro_2())

# fn call_em_parallel():
# parallelize[my_sync_fn](2)

let ns = time_function[call_em_together]() # do the same for other two
print(ns)
fn main():
async fn my_async_fn() -> Int:
sleep(2)
return 5

fn my_sync_fn():
let my_coro: Coroutine[Int] = my_async_fn()
print(my_coro())

fn call_em_together():
_ = my_sync_fn()
_ = my_sync_fn()

fn call_em_coroutine():
let my_coro_1: Coroutine[Int] = my_async_fn()
print(my_coro_1())
let my_coro_2: Coroutine[Int] = my_async_fn()
print(my_coro_2())

# fn call_em_parallel():
# parallelize[my_sync_fn](2)

let ns = time_function[call_em_together]() # do the same for other two
print(ns)
call_em_together() and call_em_coroutine() both print roughly 4 seconds as the result. call_em_parallel() prints roughly 2 seconds. Does that mean coroutines are not executed in parallel? Is there a way to execute them in parallel, like with goroutines in Go? I saw a TaskGroup mentioned in the changelog but no documentation for it exists yet, and I'm not sure how to import it. My use case is to have a blocking process/an infinite loop (e.g. a server listener) running on one coroutine , and another processes (e.g. a client making requests) executing in another in parallel
3 Replies
Jack Clayton
Jack Clayton11mo ago
Hi @a2svior there are more steps required for getting them to run in parallel. The lower level design is heavily in flux right now so we haven't documented it yet, it's not ergonomic at all right now. You can use the higher level from algorithm import parallelize for now, I know this limits the patterns you can use a lot, stay tuned for updates though.
a2svior
a2sviorOP11mo ago
Thanks for a quick reply! Makes sense. I was hoping to get some details on how to use the TaskGroup but if it's not ready for public use yet I can wait. parallelize should do it for my use case for now
ModularBot
ModularBot11mo ago
Congrats @a2svior, you just advanced to level 1!
Want results from more Discord servers?
Add your server