ModularM
Modular3y ago
3 replies
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)

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
Was this page helpful?